package com.quanyan.place.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.mapper.*;

import org.apache.commons.collections.MapUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ServletUtils;
import com.quanyan.orderpay.request.ReqOrderSave;
import com.quanyan.orderpay.request.ReqPayInfo;
import com.quanyan.orderpay.request.ReqProductDetail;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.Dict;
import com.quanyan.place.entity.DictExample;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbBizPlace;
import com.quanyan.place.entity.TbBizPlaceAttach;
import com.quanyan.place.entity.TbBizPlaceAttachExample;
import com.quanyan.place.entity.TbBizPlaceExample;
import com.quanyan.place.entity.TbBizPlaceMember;
import com.quanyan.place.entity.TbBizPlaceMemberCard;
import com.quanyan.place.entity.TbBizPlaceMemberCardExample;
import com.quanyan.place.entity.TbBizPlaceMemberCardType;
import com.quanyan.place.entity.TbBizPlaceMemberCardTypeExample;
import com.quanyan.place.entity.TbBizPlaceMemberCardTypeTicket;
import com.quanyan.place.entity.TbBizPlaceMemberExample;
import com.quanyan.place.entity.TbBizPlaceMemberOpHistory;
import com.quanyan.place.entity.TbBizPlaceMemberOpHistoryExample;
import com.quanyan.place.entity.TbBizPlaceOrder;
import com.quanyan.place.entity.TbBizPlaceOrderItem;
import com.quanyan.place.entity.TbBizPlacePayItem;
import com.quanyan.place.entity.TbCommonParameter;
import com.quanyan.place.entity.TbPlaceTicketSalePlan;
import com.quanyan.place.entity.TbPlaceTicketSalePlanExample;
import com.quanyan.place.entity.apireq.ReqMemberCardOperate;
import com.quanyan.place.entity.apireq.ReqMemberCardType;
import com.quanyan.place.entity.apireq.ReqOrderHistory;
import com.quanyan.place.entity.apireq.ReqOrderOperate;
import com.quanyan.place.entity.apiresp.RespCardPayList;
import com.quanyan.place.entity.apiresp.RespMemberCard;
import com.quanyan.place.entity.apiresp.RespMemberCardInfo;
import com.quanyan.place.entity.apiresp.RespMemberCardOperate;
import com.quanyan.place.entity.apiresp.RespMemberCardType;
import com.quanyan.place.entity.apiresp.RespPlaceInfo;
import com.quanyan.place.entity.apiresp.RespPlaceMemberCard;
import com.quanyan.place.entity.apiresp.RespPlaceMemberCardDetail;
import com.quanyan.place.entity.vo.PlaceMemberTypeVo;
import com.quanyan.place.entity.vo.ReqPlaceMemberSearch;
import com.quanyan.place.entity.vo.TbBizPlaceMemberOpHistoryVo;
import com.quanyan.place.enums.PlaceErrorCodeEnum;
import com.quanyan.place.service.BaseService;
import com.quanyan.place.service.CardNoService;
import com.quanyan.place.service.PlaceMemberService;
import com.quanyan.place.service.TbBusinessLogService;
import com.quanyan.user.request.ReqBackstageUser;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;

/**
 * Created by youxiaojia on 2016/8/23.
 */
@Service("placeMemberService")
public class PlaceMemberServiceImpl implements PlaceMemberService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TbBizPlaceMemberCardTypeMapper tbBizPlaceMemberCardTypeMapper;
    @Autowired
    private TbBizPlaceMapper tbBizPlaceMapper;
    @Autowired
    TbBizPlaceAttachMapper tbBizPlaceAttachMapper;

    @Autowired
    private DictMapper dictMapper;
    @Autowired
    TbBizPlaceMapper placeMapper;
    @Autowired
    private PlaceUnitSalePlanMapper placeUnitSalePlanMapper;
    @Autowired
    private TbBizPlaceMemberMapper tbBizPlaceMemberMapper;
    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;
    @Autowired
    private TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;
    @Autowired
    private TbAdminUserMapper tbAdminUserMapper;
    @Autowired
    private VPlaceMemberMapper vPlaceMemberMapper;

    @Autowired
    private VPlaceMapper vPlaceMapper;

    @Autowired
    UserServiceFacade userServiceFacade;
    @Autowired
    private TbBizPlaceMemberCardTypeTicketMapper tbBizPlaceMemberCardTypeTicketMapper;
    @Autowired
    private TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;
    @Autowired
    private PlaceMemberMapper placeMemberMapper;
    @Autowired
    private CardNoService cardNoService;
    @Autowired
    private BaseService baseService;
    @Value("${notify.url.payUrl}")
    private String payUrl;

    @Value("${notify.url.refundUrl}")
    private String refundUrl;

    @Value("${notify.url.exception.refundUrl}")
    private String exceptionRefundUrl;

    @Value("${notify.url.closeOrderUrl}")
    private String closeOrderUrl;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private TbBizPlaceOrderMapper tbBizPlaceOrderMapper;
    @Autowired
    private TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;
    @Autowired
    private TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

    @Autowired
    PlaceRedisTemplate placeRedisTemplate;
    @Autowired
    TbBusinessLogService businessLogService;

    @Override
    public APIResponse insertMemberType(@Validated ReqMemberCardType reqMemberType) {
        if (!StringUtils.isEmpty(reqMemberType)) {
            TbBizPlaceMemberCardType tbBizPlaceMemberCardType = new TbBizPlaceMemberCardType();
            BeanUtils.copyProperties(reqMemberType, tbBizPlaceMemberCardType);
            if (reqMemberType.getGiveAmountIsUse() == null) {
                tbBizPlaceMemberCardType.setGiveAmountIsUse(0);
            }
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqMemberType.getPlaceId());
            if (!StringUtils.isEmpty(tbBizPlace)) {
                tbBizPlaceMemberCardType.setCode(tbBizPlace.getCode());
                tbBizPlaceMemberCardType.setCreateTime(new Date());
                tbBizPlaceMemberCardType.setUpdateTime(new Date());
                if (StringUtils.isEmpty(reqMemberType.getGiveAmount())) {
                    tbBizPlaceMemberCardType.setGiveAmount(new BigDecimal(0));
                }
                if (!StringUtils.isEmpty(reqMemberType.getAvailableAll())) {
                    if (reqMemberType.getAvailableAll() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_AVAILABLE_ALL) {//0为全时段，为场馆营业时段
                        Map map = placeUnitSalePlanMapper.getPlaceUnitTime(tbBizPlace.getId(), null);
                        if (StringUtils.isEmpty(MapUtils.getString(map, "startTime"))) {
                            return APIResponse.returnFail("该场馆营业开始时间为空");
                        } else {
                            tbBizPlaceMemberCardType.setAvailableStartTime(DateTimeUtils.convertString2Date("HH:mm:ss", MapUtils.getString(map, "startTime")));
                        }
                        if (StringUtils.isEmpty(MapUtils.getString(map, "endTime"))) {
                            return APIResponse.returnFail("该场馆营业结束时间为空");
                        } else {
                            tbBizPlaceMemberCardType.setAvailableEndTime(DateTimeUtils.convertString2Date("HH:mm:ss", MapUtils.getString(map, "endTime")));
                        }
                    } else if (reqMemberType.getAvailableAll() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_AVAILABLE_PART) {//1为指定时段
                        if (!StringUtils.isEmpty(reqMemberType.getAvailableStartTime())) {
                            tbBizPlaceMemberCardType.setAvailableStartTime(DateTimeUtils.convertString2Date("HH:mm:ss", reqMemberType.getAvailableStartTime()));
                        } else {
                            return APIResponse.returnFail("指定开始时间不能为空");
                        }
                        if (!StringUtils.isEmpty(reqMemberType.getAvailableEndTime())) {
                            tbBizPlaceMemberCardType.setAvailableEndTime(DateTimeUtils.convertString2Date("HH:mm:ss", reqMemberType.getAvailableEndTime()));
                        } else {
                            return APIResponse.returnFail("指定结束时间不能为空");
                        }
                    }
                }
                if (!StringUtils.isEmpty(reqMemberType.getCardDesc())) {
                    tbBizPlaceMemberCardType.setDescription(reqMemberType.getCardDesc());
                }
                if (!StringUtils.isEmpty(reqMemberType.getSourceType())) {
                    tbBizPlaceMemberCardType.setSourceType(reqMemberType.getSourceType());
                }
                if (!PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(reqMemberType.getType())){
                    if(null != reqMemberType.getIsSupportTickets()){
                        tbBizPlaceMemberCardType.setIsSupportTickets(reqMemberType.getIsSupportTickets());
                    }else{
                        tbBizPlaceMemberCardType.setIsSupportTickets((byte)0);
                    }
                }else{
                    tbBizPlaceMemberCardType.setIsSupportTickets((byte)1);
                }

                tbBizPlaceMemberCardType.setCategoryIds(JSON.toJSONString(reqMemberType.getCategoryIds()));
                tbBizPlaceMemberCardType.setIsDelete(Constants.IS_DELETE_FALSE);
                //次卡运动类型
                if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(reqMemberType.getType())) {
                    if (CollectionUtils.isEmpty(reqMemberType.getTicketIds())) {
                        return APIResponse.returnFail("请选择门票");
                    }
                    TbPlaceTicketSalePlanExample ticketSalePlanExample = new TbPlaceTicketSalePlanExample();
                    TbPlaceTicketSalePlanExample.Criteria ticketSalePlanCriteria = ticketSalePlanExample.createCriteria();
                    ticketSalePlanCriteria.andIdIn(reqMemberType.getTicketIds());
                    List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlanList = tbPlaceTicketSalePlanMapper.selectByExample(ticketSalePlanExample);
                    List categoryIds = new ArrayList();
                    for (TbPlaceTicketSalePlan tbPlaceTicketSalePlan : tbPlaceTicketSalePlanList) {
                        categoryIds.add(tbPlaceTicketSalePlan.getCategoryId());
                    }
                    //次卡支持的门票运动类型
                    tbBizPlaceMemberCardType.setCategoryIds(JSON.toJSONString(categoryIds));
                }
                if (null == tbBizPlaceMemberCardType.getDiscount()){
                    tbBizPlaceMemberCardType.setDiscount(100.00);
                }
                int flag = tbBizPlaceMemberCardTypeMapper.insert(tbBizPlaceMemberCardType);
                //次卡关联门票
                if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(reqMemberType.getType())) {
                    if (CollectionUtils.isEmpty(reqMemberType.getTicketIds())) {
                        return APIResponse.returnFail("请选择门票");
                    }
                    //次卡关联多张门票
                    for (Integer ticketId : reqMemberType.getTicketIds()) {
                        TbBizPlaceMemberCardTypeTicket tbBizPlaceMemberCardTypeTicket = new TbBizPlaceMemberCardTypeTicket();
                        tbBizPlaceMemberCardTypeTicket.setCardTypeId(tbBizPlaceMemberCardType.getId());
                        tbBizPlaceMemberCardTypeTicket.setTicketId(ticketId);
                        tbBizPlaceMemberCardTypeTicket.setCreateTime(new Date());
                        tbBizPlaceMemberCardTypeTicketMapper.insert(tbBizPlaceMemberCardTypeTicket);
                    }
                }
                return APIResponse.returnSuccess(flag > 0 ? true : false);
            } else {
                return APIResponse.returnFail("无此场馆");
            }
        }
        return APIResponse.returnFail("添加失败");
    }

    @Override
    public APIResponse updateMemberType(ReqMemberCardType reqMemberType) {
        if (!StringUtils.isEmpty(reqMemberType)) {
            TbBizPlaceMemberCardType tbBizPlaceMemberCardType = new TbBizPlaceMemberCardType();
            BeanUtils.copyProperties(reqMemberType, tbBizPlaceMemberCardType);
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqMemberType.getPlaceId());
            if (!StringUtils.isEmpty(tbBizPlace)) {
                tbBizPlaceMemberCardType.setCode(tbBizPlace.getCode());
                tbBizPlaceMemberCardType.setCreateTime(new Date());
                tbBizPlaceMemberCardType.setUpdateTime(new Date());
                if (!StringUtils.isEmpty(reqMemberType.getAvailableAll())) {
                    if (reqMemberType.getAvailableAll() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_AVAILABLE_ALL) {//0为全时段，为场馆营业时段
                        Map map = placeUnitSalePlanMapper.getPlaceUnitTime(tbBizPlace.getId(), null);
                        if (StringUtils.isEmpty(MapUtils.getString(map, "startTime"))) {
                            return APIResponse.returnFail("该场馆营业开始时间为空");
                        } else {
                            tbBizPlaceMemberCardType.setAvailableStartTime(DateTimeUtils.convertString2Date("HH:mm:ss", MapUtils.getString(map, "startTime")));
                        }
                        if (StringUtils.isEmpty(MapUtils.getString(map, "endTime"))) {
                            return APIResponse.returnFail("该场馆营业结束时间为空");
                        } else {
                            tbBizPlaceMemberCardType.setAvailableEndTime(DateTimeUtils.convertString2Date("HH:mm:ss", MapUtils.getString(map, "endTime")));
                        }

                    } else if (reqMemberType.getAvailableAll() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_AVAILABLE_PART) {//1为指定时段
                        if (!StringUtils.isEmpty(reqMemberType.getAvailableStartTime())) {
                            tbBizPlaceMemberCardType.setAvailableStartTime(DateTimeUtils.convertString2Date("HH:mm:ss", reqMemberType.getAvailableStartTime()));
                        } else {
                            return APIResponse.returnFail("指定开始时间不能为空");
                        }
                        if (!StringUtils.isEmpty(reqMemberType.getAvailableEndTime())) {
                            tbBizPlaceMemberCardType.setAvailableEndTime(DateTimeUtils.convertString2Date("HH:mm:ss", reqMemberType.getAvailableEndTime()));
                        } else {
                            return APIResponse.returnFail("指定结束时间不能为空");
                        }
                    }
                }
                int flag = tbBizPlaceMemberCardTypeMapper.updateByPrimaryKeySelective(tbBizPlaceMemberCardType);
                return APIResponse.returnSuccess(flag > 0 ? true : false);
            } else {
                return APIResponse.returnFail("无此场馆");
            }
        }
        return APIResponse.returnFail("更新失败");
    }

    /**
     * 更新会员卡类型名称，会员卡类型描述
     *
     * @param memberCardTypeName
     * @param memberCardTypeDescription
     * @return
     */
    @Override
    public APIResponse updateMemberTypeNameAndDescription(Integer memberCardTypeId, String memberCardTypeName, String memberCardTypeDescription,
                                                          Double discount, BigDecimal giveAmount, BigDecimal initAmount) {
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = new TbBizPlaceMemberCardType();
        tbBizPlaceMemberCardType.setId(memberCardTypeId);
        tbBizPlaceMemberCardType.setName(memberCardTypeName);
        tbBizPlaceMemberCardType.setDescription(memberCardTypeDescription);
        if (discount != null && discount > 0) {
            tbBizPlaceMemberCardType.setDiscount(discount);//折扣
        }
        if (giveAmount != null && giveAmount.compareTo(BigDecimal.ZERO) > 0) {
            tbBizPlaceMemberCardType.setGiveAmount(giveAmount);//赠送金额
        }
        if (initAmount != null && initAmount.compareTo(BigDecimal.ZERO) > 0) {
            tbBizPlaceMemberCardType.setInitAmount(initAmount);//充值
        }
        int flag1 = tbBizPlaceMemberCardTypeMapper.updateByPrimaryKeySelective(tbBizPlaceMemberCardType);
        //修改会员卡表卡类型名称
        int flag2 = 0;
        TbBizPlaceMemberCardExample example1 = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andCardTypeIdEqualTo(memberCardTypeId);
        if (tbBizPlaceMemberCardMapper.countByExample(example1) > 0) {
            TbBizPlaceMemberCard tbBizPlaceMemberCard = new TbBizPlaceMemberCard();
            tbBizPlaceMemberCard.setCardName(memberCardTypeName);
            flag2 = tbBizPlaceMemberCardMapper.updateByExampleSelective(tbBizPlaceMemberCard, example1);
        }
        //修改明细表卡类型名称
        int flag3 = 0;
        TbBizPlaceMemberOpHistoryExample example2 = new TbBizPlaceMemberOpHistoryExample();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andCardTypeIdEqualTo(memberCardTypeId);
        if (tbBizPlaceMemberOpHistoryMapper.countByExample(example2) > 0) {
            TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
            tbBizPlaceMemberOpHistory.setCardTypeName(memberCardTypeName);
            flag3 = tbBizPlaceMemberOpHistoryMapper.updateByExampleSelective(tbBizPlaceMemberOpHistory, example2);
        }

        return APIResponse.returnSuccess((flag1 == 1) && (flag2 > 0) && (flag3 > 0) ? true : false);
    }

    public APIResponse<PageObj<List<RespMemberCardType>>> queryMemberTypeListByConditions(PlaceMemberTypeVo placeMemberTypeVo) {
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer oldPageNum = placeMemberTypeVo.getPageNum();
        if (!StringUtils.isEmpty(placeMemberTypeVo.getPageSize())) {
            pageSize = placeMemberTypeVo.getPageSize();
        }
        if (!StringUtils.isEmpty(placeMemberTypeVo.getPageNum())) {
            pageNum = placeMemberTypeVo.getPageNum() * pageSize;
            placeMemberTypeVo.setPageNum(pageNum);
        }

        placeMemberTypeVo.setPageSize(pageSize);
        placeMemberTypeVo.setPageNum(pageNum);

        if (!StringUtils.isEmpty(placeMemberTypeVo.getPlace())){
            placeMemberTypeVo.setPlace(placeMemberTypeVo.getPlace().trim());
        }


        int total = vPlaceMemberMapper.getRespMemberCardTypesCount(placeMemberTypeVo);
        if (total == 0){
            return APIResponse.returnSuccess(new PageObj<List<RespMemberCardType>>());
        }



        List<RespMemberCardType> list = vPlaceMemberMapper.getRespMemberCardTypesByTerm(placeMemberTypeVo);
        list = this.tb2RespMemberCardType(list);
        PageObj<List<RespMemberCardType>> result = PageObj.create(total, oldPageNum, pageSize, list);
        return APIResponse.returnSuccess(result);
    }

    private List<RespMemberCardType> tb2RespMemberCardType(List<RespMemberCardType> tbBizPlaceMemberCardTypeList) {
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardTypeList)) {
            List<RespMemberCardType> list = new ArrayList<>();
            Map<String, String> map = getDictDisplayName(PlaceConstants.PLACE_MEMBER_CARD_TYPE);
            for (RespMemberCardType tbBizPlaceMemberCardType : tbBizPlaceMemberCardTypeList) {
                RespMemberCardType respMemberCardType = new RespMemberCardType();
                BeanUtils.copyProperties(tbBizPlaceMemberCardType, respMemberCardType);
                if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getPlaceId())) {
                    TbBizPlace basePlace = placeMapper.selectByPrimaryKey(tbBizPlaceMemberCardType.getPlaceId());
                    if (!StringUtils.isEmpty(basePlace)) {
                        respMemberCardType.setPlaceName(basePlace.getName());//Todo 待优化
                        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getType())) {
                            respMemberCardType.setMemberType(MapUtils.getString(map, tbBizPlaceMemberCardType.getType().toString()));
                        }
                        respMemberCardType.setCategoryIds(JSON.parseObject(tbBizPlaceMemberCardType.getStrCategoryIds(), List.class));
                    }
                }
                //判断会员卡类型是否可用
                respMemberCardType.setIsUse(isMemberCardTypeUse(tbBizPlaceMemberCardType.getId(),
                        tbBizPlaceMemberCardType.getType(),tbBizPlaceMemberCardType.getPlaceId()));
                list.add(respMemberCardType);
            }
            return list;
        }
        return null;
    }

    public APIResponse<PageObj<List<RespMemberCardType>>> queryMemberTypeListByConditions0(PlaceMemberTypeVo placeMemberTypeVo) {
        TbBizPlaceMemberCardTypeExample example = new TbBizPlaceMemberCardTypeExample();
        TbBizPlaceMemberCardTypeExample.Criteria criteria1 = example.createCriteria();


        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        if (!StringUtils.isEmpty(placeMemberTypeVo.getPageNum())) {
            pageNum = placeMemberTypeVo.getPageNum();
        }
        if (!StringUtils.isEmpty(placeMemberTypeVo.getPageSize())) {
            pageSize = placeMemberTypeVo.getPageSize();
        }
        //按场馆编号，名称模糊查询
        String place = placeMemberTypeVo.getPlace();
        if (!StringUtils.isEmpty(place)) {
            List<Integer> ids = new ArrayList<>();
            TbBizPlaceExample example1 = new TbBizPlaceExample();
            TbBizPlaceExample.Criteria criteria3 = example1.createCriteria();
            //场馆名称模糊查询
            criteria3.andNameLike("%" + place.trim() + "%");
            TbBizPlaceExample.Criteria criteria4 = example1.createCriteria();
            //场馆编号模糊查询
            criteria4.andCodeLike("%" + place.trim() + "%");
            example1.or(criteria4);
            List<TbBizPlace> list = tbBizPlaceMapper.selectByExample(example1);
            int len = list.size();
            if (len != 0) {
                for (int i = 0; i < len; i++) {
                    ids.add(list.get(i).getId());
                }
                criteria1.andPlaceIdIn(ids);
                //criteria2.andPlaceIdIn(ids);
            } else {
                return APIResponse.returnFail("无此场馆");
            }
        }
        //卡类型查询
        Integer type = placeMemberTypeVo.getType();
        if (!StringUtils.isEmpty(type)) {
            if (type.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE) {//储值卡
                criteria1.andTypeEqualTo(type.byteValue());
                // criteria2.andTypeEqualTo(type.byteValue());
            }
            if (type.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT) {//折扣卡
                criteria1.andTypeEqualTo(type.byteValue());
                //criteria2.andTypeEqualTo(type.byteValue());
            }
            if (type.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT) {//储值折扣卡
                criteria1.andTypeEqualTo(type.byteValue());
                //criteria2.andTypeEqualTo(type.byteValue());
            }
            if (type.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER) {//次卡
                criteria1.andTypeEqualTo(type.byteValue());
                //criteria2.andTypeEqualTo(type.byteValue());
            }
        }
        //卡状态查询
        Integer status = placeMemberTypeVo.getStatus();
        if (!StringUtils.isEmpty(status)) {
            if (status.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_YES) {//可用
                criteria1.andStatusEqualTo(status.byteValue());
                //criteria2.andStatusEqualTo(status.byteValue());
            }
            if (status.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_NO) {//停用
                criteria1.andStatusEqualTo(status.byteValue());
                //criteria2.andStatusEqualTo(status.byteValue());
            }
        }
        //来源类型 1：普通会员 2：议价会员
        Byte sourceType = placeMemberTypeVo.getSourceType();
        if (!StringUtils.isEmpty(sourceType)) {
            if (sourceType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_GENERAL_MEMBER) {//普通会员
                criteria1.andSourceTypeEqualTo(sourceType.byteValue());
            }
            if (sourceType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_BARGAINING_MEMBER) {//议价会员
                criteria1.andSourceTypeEqualTo(sourceType.byteValue());
            }
        }
        criteria1.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        Integer placeId = placeMemberTypeVo.getPlaceId();
        if (!StringUtils.isEmpty(placeId)) {
            criteria1.andPlaceIdEqualTo(placeId);
        }
        //场馆id升序 , id降序
        example.setOrderByClause("place_id asc,id desc");
        int total = tbBizPlaceMemberCardTypeMapper.countByExample(example);
        example.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbBizPlaceMemberCardType> list = tbBizPlaceMemberCardTypeMapper.selectByExample(example);
        List<RespMemberCardType> respMemberCardTypeList = this.tbMemberCardType2RespMemberCardType(list);
        PageObj<List<RespMemberCardType>> result = PageObj.create(total, pageNum, pageSize, respMemberCardTypeList);
        return APIResponse.returnSuccess(result);
    }

    @Override
    public APIResponse<RespMemberCardType> getMemberTypeDetailById(Integer id) {
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(id);
        if (tbBizPlaceMemberCardType.getIsDelete() == Constants.IS_DELETE_FALSE) {
            List<TbBizPlaceMemberCardType> tbBizPlaceMemberCardTypes = new ArrayList<>();
            tbBizPlaceMemberCardTypes.add(tbBizPlaceMemberCardType);
            List<RespMemberCardType> respMemberCardTypes = tbMemberCardType2RespMemberCardType(tbBizPlaceMemberCardTypes);
            return APIResponse.returnSuccess(respMemberCardTypes.get(0));
        }
        return APIResponse.returnFail("没有此会员类型");
    }

    @Override
    public APIResponse delMemberTypeById(Integer id) {
        int flag = tbBizPlaceMemberCardTypeMapper.deleteByPrimaryKey(id);
        if (flag == 1) {
            return APIResponse.returnSuccess(true);
        }
        return APIResponse.returnFail("删除会员类型失败");
    }

    @Override
    public APIResponse updateMemberTypeStatusById(Integer id, byte status) {
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(id);
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType)) {
            if (tbBizPlaceMemberCardType.getIsDelete() == Constants.IS_DELETE_FALSE) {
                tbBizPlaceMemberCardType.setStatus(status);
                int flag = tbBizPlaceMemberCardTypeMapper.updateByPrimaryKeySelective(tbBizPlaceMemberCardType);
                if (flag == 1) {
                    return APIResponse.returnSuccess(true);
                }
            }
        }
        return APIResponse.returnFail("更新会员类型状态失败");
    }

    @Override
    public APIResponse<?> getMemberTypeDictDisplayName() {
        Map map = getDictDisplayName(PlaceConstants.PLACE_MEMBER_CARD_TYPE);
        return APIResponse.returnSuccess(map);
    }

    @Override
    public Integer getUidByNameAndPhone(String userName, String phone) {
        TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
        TbBizPlaceMemberExample.Criteria criteria = example.createCriteria();
        //criteria.andUserNameEqualTo(userName.trim());//提升用户体验，名称不过滤
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andMobileEqualTo(phone.trim());
        example.setDistinct(true);
        List<TbBizPlaceMember> tbBizPlaceMemberList = tbBizPlaceMemberMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberList)) {
            return tbBizPlaceMemberList.get(0).getUid();
        }
        return null;
    }

    /**
     * 开单获取用户所有相关会员卡
     *
     * @param userName
     * @param phone
     * @param placeId
     * @param categoryId
     * @return
     */
    @Override
    public APIResponse<List<RespMemberCard>> billingPlaceGetMemberCardList(String userName, String phone, Integer placeId, Integer categoryId) {
        Integer uid = this.getUidByNameAndPhone(userName, phone);
        if (!StringUtils.isEmpty(uid)) {
            // 通馆会员做特殊处理，可以共享会员  这个个性化需求就是大坑
            List<Integer> placeIdList = new ArrayList<Integer>();
            boolean isVipShare = false;
            if (checkIsShareVip(placeId)){
                placeIdList = vPlaceMapper.getShareVipPlaceIds(placeId);
                if (placeIdList.size() > 1){
                    isVipShare = true;
                }
            }
            //判断是不是该场馆会员
            if (isPlaceMember(uid, placeId, categoryId, 1)) {
                TbBizPlaceMemberCardTypeExample example1 = new TbBizPlaceMemberCardTypeExample();
                TbBizPlaceMemberCardTypeExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                //criteria1.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_YES); 不过滤会员卡禁用情况
                /*criteria1.andAvailableStartTimeLessThan(new Date());//可用时段
                criteria1.andAvailableEndTimeGreaterThan(new Date());*/
                if (categoryId != null) {
                    criteria1.andCategoryIdsLike("%" + categoryId + "%");//运动类型
                }
                if (isVipShare){
                    criteria1.andPlaceIdIn(placeIdList);
                } else {
                    criteria1.andPlaceIdEqualTo(placeId);
                }
                List typeList = new ArrayList();
                typeList.add(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE);
                typeList.add(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT);
                typeList.add(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT);
                criteria1.andTypeIn(typeList);//开单获取储值卡,折扣卡，储值折扣 //TODO 包场次卡没有考虑
                List<TbBizPlaceMemberCardType> tbBizPlaceMemberCardTypeList = tbBizPlaceMemberCardTypeMapper.selectByExample(example1);
                if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardTypeList)) {
                    List<Integer> cardTypeIds = new ArrayList<>();
                    for (TbBizPlaceMemberCardType tbBizPlaceMemberCardType : tbBizPlaceMemberCardTypeList) {
                        cardTypeIds.add(tbBizPlaceMemberCardType.getId());
                    }
                    TbBizPlaceMemberCardExample example2 = new TbBizPlaceMemberCardExample();
                    TbBizPlaceMemberCardExample.Criteria criteria2 = example2.createCriteria();
                    TbBizPlaceMemberCardExample.Criteria criteria3 = example2.or();
                    criteria2.andCardTypeIdIn(cardTypeIds);
                    criteria2.andMemberUidEqualTo(uid);
                    if (isVipShare){
                        criteria2.andPlaceIdIn(placeIdList);
                    } else {
                        criteria2.andPlaceIdEqualTo(placeId);
                    }
                    criteria2.andDeadLineTimeGreaterThan(new Date());//判断截止日期 --指定有效期
                    criteria2.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                    if (categoryId != null) {
                        criteria2.andCategoryIdsLike("%" + categoryId + "%");//运动类型
                    }
                    /*criteria2.andAvailableStartTimeLessThan(new Date());//可用时段
                    criteria2.andAvailableEndTimeGreaterThan(new Date());*/
                    criteria2.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);

                    criteria3.andCardTypeIdIn(cardTypeIds);
                    criteria3.andMemberUidEqualTo(uid);
                    if (isVipShare){
                        criteria3.andPlaceIdIn(placeIdList);
                    } else {
                        criteria3.andPlaceIdEqualTo(placeId);
                    }
                    criteria3.andDeadLineTimeIsNull();//判断截止日期 --无限制
                    criteria3.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                    if (categoryId != null) {
                        criteria3.andCategoryIdsLike("%" + categoryId + "%");//运动类型
                    }
                    /*criteria3.andAvailableStartTimeLessThan(new Date());//可用时段
                    criteria3.andAvailableEndTimeGreaterThan(new Date());*/
                    criteria3.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
                   
                    List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(example2);
                    List<RespMemberCard> respMemberCardList = tbBizPlaceMemberCardList2RespMemberCardList(tbBizPlaceMemberCardList);
                    return APIResponse.returnSuccess(respMemberCardList);
                }
            } else {
                return APIResponse.returnFail("不是该场馆该运动类别会员");
            }
        } else {
            return APIResponse.returnFail("uid不能为null");
        }
        return APIResponse.returnFail("订场获取会员失败");
    }
    
    
    @Override
    public APIResponse<List<RespMemberCardInfo>> queryMemberCardList(String key, Integer placeId, Integer categoryId) {
            List<Integer> placeIdList = new ArrayList<Integer>();
            //是否是共享会员场馆
            if (checkIsShareVip(placeId)){
                placeIdList = vPlaceMapper.getShareVipPlaceIds(placeId);
            }
            ReqPlaceMemberSearch reqMemberSearch = new ReqPlaceMemberSearch();
            reqMemberSearch.setPlaceId(placeId);
            reqMemberSearch.setPlaceIdList(placeIdList);
            reqMemberSearch.setKey(key);
            reqMemberSearch.setCategoryId(categoryId);
            reqMemberSearch.setCardTypeList(Arrays.asList(1,2,3));
            return APIResponse.returnSuccess(vPlaceMemberMapper.queryPlaceMemberCardByCondition(reqMemberSearch));
    }
    

    private List<RespMemberCard> tbBizPlaceMemberCardList2RespMemberCardList(List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList) {
        List<RespMemberCard> respMemberCardList = new ArrayList<RespMemberCard>();
        if (CollectionUtils.isEmpty(tbBizPlaceMemberCardList)){
            return null;
        }
        for (TbBizPlaceMemberCard tbBizPlaceMemberCard : tbBizPlaceMemberCardList){
            RespMemberCard respMemberCard = new RespMemberCard();
            BeanUtils.copyProperties(tbBizPlaceMemberCard,respMemberCard);
            TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper
                    .selectByPrimaryKey(tbBizPlaceMemberCard.getCardTypeId());
            respMemberCard.setInitAmount(tbBizPlaceMemberCardType.getInitAmount());
            respMemberCard.setInitGiveAmount(tbBizPlaceMemberCardType.getGiveAmount());
            respMemberCardList.add(respMemberCard);
        }
        return respMemberCardList;
    }
    /**
     * 购物车获取会员卡列表
     *
     * @param placeId
     * @return
     */
    public APIResponse<List<RespMemberCard>> shoppingCardGetMemberCardList(String userName, String phone, Integer placeId) {
        Integer uid = this.getUidByNameAndPhone(userName, phone);
        if (!StringUtils.isEmpty(uid)) {
            // 通馆会员做特殊处理，可以共享会员  这个个性化需求就是大坑
            List<Integer> placeIdList = new ArrayList<Integer>();
            boolean isVipShare = false;
            if (checkIsShareVip(placeId)){
                placeIdList = vPlaceMapper.getShareVipPlaceIds(placeId);
                if (placeIdList.size() > 1){
                    isVipShare = true;
                }
            }
            Map map = new HashMap();
            map.put("uid",uid);
            map.put("placeIdList",placeIdList);
            map.put("placeId",placeId);
            map.put("isVipShare",isVipShare);
            List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList1 = new ArrayList<>();
            tbBizPlaceMemberCardList1 = placeMemberMapper.selectMemberCardByCondition(map);
            List<RespMemberCard> respMemberCardList1 = tbBizPlaceMemberCardList2RespMemberCardList(tbBizPlaceMemberCardList1);
            if(CollectionUtils.isEmpty(respMemberCardList1)){
                return APIResponse.returnFail("该会员名下无可用会员卡");
            }else {
                return APIResponse.returnSuccess(respMemberCardList1);
            }
        } else {
            return APIResponse.returnFail("uid不能为null");
        }

    }
    /**
     * 商品售卖会员卡消费获取用户所有相关会员卡
     *
     * @param userName
     * @param phone
     * @param placeId
     * @param categoryId
     * @return
     */
    @Override
    public APIResponse<List<RespPlaceMemberCard>> goodsConsumeGetMemberCardList(String userName, String phone, Integer placeId, Integer categoryId) {
        Integer uid = this.getUidByNameAndPhone(userName, phone);
        if (!StringUtils.isEmpty(uid)) {
            List<Integer> placeIdList = new ArrayList<Integer>();
            boolean isVipShare = false;
            if (checkIsShareVip(placeId)){
                placeIdList = vPlaceMapper.getShareVipPlaceIds(placeId);
                if (placeIdList.size() > 1){
                    isVipShare = true;
                }
            }
            //判断是不是该场馆会员
            if (isPlaceMember(uid, placeId, categoryId, 1)) {
                TbBizPlaceMemberCardTypeExample example1 = new TbBizPlaceMemberCardTypeExample();
                TbBizPlaceMemberCardTypeExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                //criteria1.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_YES); 不过滤会员卡禁用情况
                /*criteria1.andAvailableStartTimeLessThan(new Date());//可用时段
                criteria1.andAvailableEndTimeGreaterThan(new Date());*/
                if (categoryId != null) {
                    criteria1.andCategoryIdsLike("%" + categoryId + "%");//运动类型
                }
                if (isVipShare){
                    criteria1.andPlaceIdIn(placeIdList);
                } else {
                    criteria1.andPlaceIdEqualTo(placeId);
                }
                List typeList = new ArrayList();
                typeList.add(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE);
                typeList.add(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT);
                typeList.add(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT);
                criteria1.andTypeIn(typeList);//开单获取储值卡,折扣卡，储值折扣 //TODO 包场次卡没有考虑
                List<TbBizPlaceMemberCardType> tbBizPlaceMemberCardTypeList = tbBizPlaceMemberCardTypeMapper.selectByExample(example1);
                if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardTypeList)) {
                    List<Integer> cardTypeIds = new ArrayList<>();
                    List<Integer> giveAmountIsUseList = new ArrayList<>();
                    for (TbBizPlaceMemberCardType tbBizPlaceMemberCardType : tbBizPlaceMemberCardTypeList) {
                        cardTypeIds.add(tbBizPlaceMemberCardType.getId());
                        giveAmountIsUseList.add(tbBizPlaceMemberCardType.getGiveAmountIsUse());
                    }
                    TbBizPlaceMemberCardExample example2 = new TbBizPlaceMemberCardExample();
                    TbBizPlaceMemberCardExample.Criteria criteria2 = example2.createCriteria();
                    TbBizPlaceMemberCardExample.Criteria criteria3 = example2.createCriteria();
                    criteria2.andCardTypeIdIn(cardTypeIds);
                    criteria2.andMemberUidEqualTo(uid);

                    if (isVipShare){
                        criteria2.andPlaceIdIn(placeIdList);
                    } else {
                        criteria2.andPlaceIdEqualTo(placeId);
                    }
                    criteria2.andDeadLineTimeGreaterThan(new Date());//判断截止日期 --指定有效期
                    criteria2.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                    if (categoryId != null) {
                        criteria2.andCategoryIdsLike("%" + categoryId + "%");//运动类型
                    }
                    /*criteria2.andAvailableStartTimeLessThan(new Date());//可用时段
                    criteria2.andAvailableEndTimeGreaterThan(new Date());*/
                    criteria2.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);

                    criteria3.andCardTypeIdIn(cardTypeIds);
                    criteria3.andMemberUidEqualTo(uid);

                    if (isVipShare){
                        criteria3.andPlaceIdIn(placeIdList);
                    } else {
                        criteria3.andPlaceIdEqualTo(placeId);
                    }
                    criteria3.andDeadLineTimeIsNull();//判断截止日期 --无限制
                    criteria3.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                    criteria3.andCategoryIdsLike("%" + categoryId + "%");//运动类型
                    /*criteria3.andAvailableStartTimeLessThan(new Date());//可用时段
                    criteria3.andAvailableEndTimeGreaterThan(new Date());*/
                    criteria3.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);

                    example2.or(criteria3);
                    List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(example2);
                    List<RespPlaceMemberCard> resplist = new ArrayList<>();
                    for (TbBizPlaceMemberCard vo : tbBizPlaceMemberCardList) {
                        RespPlaceMemberCard respVo = new RespPlaceMemberCard();
                        respVo.setCardTypeId(vo.getCardTypeId());
                        respVo.setCardType(vo.getCardType());
                        respVo.setGiveAmount(vo.getGiveAmount());
                        respVo.setPlaceId(vo.getPlaceId());
                        respVo.setAmount(vo.getAmount());
                        respVo.setCardName(vo.getCardName());
                        respVo.setDeadLineTime(vo.getDeadLineTime());
                        respVo.setAvailableEndTime(vo.getAvailableEndTime());
                        respVo.setAvailableStartTime(vo.getAvailableStartTime());
                        respVo.setSourceType(vo.getSourceType());
                        respVo.setSurplusGiveAmount(vo.getSurplusGiveAmount());
                        respVo.setSurplusAmount(vo.getSurplusAmount());
                        respVo.setDiscount(vo.getDiscount());
                        respVo.setCategoryIds(vo.getCategoryIds());
                        respVo.setSurplusNumbers(vo.getSurplusNumbers());
                        respVo.setMemberUid(vo.getMemberUid());
                        respVo.setMemo(vo.getMemo());
                        respVo.setId(vo.getId());
                        respVo.setIsOldMember(vo.getIsOldMember());
                        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(vo.getCardTypeId());
                        respVo.setInitAmount(tbBizPlaceMemberCardType.getInitAmount());
                        respVo.setInitGiveAmount(tbBizPlaceMemberCardType.getGiveAmount());
                        respVo.setDisplayName(vo.getDisplayName());
                        resplist.add(respVo);
                    }

                  /*  for (RespPlaceMemberCard cardVo:resplist){
                        for (Integer i:cardTypeIds){
                            if (cardVo.getCardTypeId().intValue()==i){
                            cardVo.setGiveAmountIsUse(giveAmountIsUseList.get(i));
                            }
                        }
                    }*/
                    for (int i = 0; i < resplist.size(); i++) {
                        for (int j = 0; j < cardTypeIds.size(); j++) {
                            if (resplist.get(i).getCardTypeId().intValue() == cardTypeIds.get(j).intValue()) {
                                resplist.get(i).setGiveAmountIsUse(giveAmountIsUseList.get(j));
                            }
                        }
                    }
                    // List<TbBizPlaceMemberCard> list =new ArrayList<>();
                    // list.addAll(tbBizPlaceMemberCardList);
                    return APIResponse.returnSuccess(resplist);
                }
            } else {
                return APIResponse.returnFail("不是该场馆会员");
            }
        } else {
            return APIResponse.returnFail("uid不能为null");
        }
        return APIResponse.returnFail("订场获取会员失败");
    }


    @Override
    public TbBizPlaceMemberCard getTbBizPlaceMemberCardById(Integer id) {
        if (!StringUtils.isEmpty(id)) {
            TbBizPlaceMemberCardExample example = new TbBizPlaceMemberCardExample();
            TbBizPlaceMemberCardExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(id);
            example.setOrderByClause(" id for update ");//会员卡加锁
            List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(example);
            return tbBizPlaceMemberCardList.get(0);
//            TbBizPlaceMemberCard tbBizPlaceMemberCard = tbBizPlaceMemberCardMapper.selectByPrimaryKey(id);
//            return tbBizPlaceMemberCard;
        }
        return null;
    }

    @Override
    public boolean isPlaceMember(Integer uid, Integer placeId, Integer categoryId, Integer source) {//source 1: 商家端 0:app
        List<Integer> placeIdList = null;
        // 通馆做特殊处理
        if (checkIsShareVip(placeId)){
            placeIdList = vPlaceMapper.getShareVipPlaceIds(placeId);
        }
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andMemberUidEqualTo(uid);
        if (null != placeIdList && placeIdList.size() > 1){
            // 通馆共享会员
            tbBizPlaceMemberCardCriteria.andPlaceIdIn(placeIdList) ;
        } else {
            tbBizPlaceMemberCardCriteria.andPlaceIdEqualTo(placeId);
        }
        tbBizPlaceMemberCardCriteria.andDeadLineTimeGreaterThan(new Date());//判断截止日期
        tbBizPlaceMemberCardCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if (categoryId != null) {
            tbBizPlaceMemberCardCriteria.andCategoryIdsLike("%" + categoryId + "%");//运动类型
        }
        tbBizPlaceMemberCardCriteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        tbBizPlaceMemberCardCriteria.andCardTypeNotEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER);//过滤次卡
        /*if (source.intValue() == 0) {
            tbBizPlaceMemberCardCriteria.andSourceTypeNotEqualTo(PlaceConstants.CLUB_MEMBER);//过滤议价会员（俱乐部会员）
        }*/
       /* tbBizPlaceMemberCardCriteria.andAvailableStartTimeLessThan(new Date());//可用时段
        tbBizPlaceMemberCardCriteria.andAvailableEndTimeGreaterThan(new Date());*/
        int count = tbBizPlaceMemberCardMapper.countByExample(tbBizPlaceMemberCardExample);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 检查场馆是否共享会员
     * @param placeId
     * @return
     */
    public boolean checkIsShareVip(Integer placeId) {
        TbBizPlaceAttach placeAttach = this.getBizPlaceAttach(placeId);
        if (null != placeAttach &&
                null != placeAttach.getIsVipShare() &&
                Constants.BYTE_ONE == placeAttach.getIsVipShare()){
            return true;
        }
        return false;
    }

    @Override
    public List<TbBizPlaceMemberCard> getPlaceMemberInfo(Integer uid, Integer placeId, Integer categoryId, boolean isNeedNumberCard) {
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andMemberUidEqualTo(uid);
        List<Integer> placeIdList = null;
        // 通馆做特殊处理
        if (checkIsShareVip(placeId)){
            placeIdList = this.getShareVipPlaceIds(placeId);
        }
        if (null != placeIdList && placeIdList.size() > 1){
            tbBizPlaceMemberCardCriteria.andPlaceIdIn(placeIdList) ;
        } else {
            tbBizPlaceMemberCardCriteria.andPlaceIdEqualTo(placeId);
        }
        tbBizPlaceMemberCardCriteria.andDeadLineTimeGreaterThan(new Date());//判断截止日期
        tbBizPlaceMemberCardCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        tbBizPlaceMemberCardCriteria.andCategoryIdsLike("%" + categoryId + "%");//运动类型
        //tbBizPlaceMemberCardCriteria.andSourceTypeEqualTo(PlaceConstants.PLACE_MEMBER);
        tbBizPlaceMemberCardCriteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        if (!isNeedNumberCard) {
            tbBizPlaceMemberCardCriteria.andCardTypeNotEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER);
        }
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
        return tbBizPlaceMemberCardList;
    }

    /**
     * 根据会员卡类型ID获取会员卡类型
     *
     * @param cardTypeId
     * @return
     */
    @Override
    public TbBizPlaceMemberCardType getMemberTypeById(Integer cardTypeId) {
        return tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(cardTypeId);
    }

    /**
     * 增加场馆会员
     *
     * @param member
     */
    @Override
    public void addPlaceMember(TbBizPlaceMember member) {
        if (null != member) {
            tbBizPlaceMemberMapper.insertSelective(member);
        }
    }

    /**
     * 增加会员卡
     *
     * @param memberCard
     */
    @Override
    public void addPlaceMemberCard(TbBizPlaceMemberCard memberCard) {
        if (null != memberCard) {
            tbBizPlaceMemberCardMapper.insertSelective(memberCard);
        }
    }

    /**
     * 判断会员卡是否已存在
     *
     * @param placeId
     * @param cardTypeId
     * @param uid
     * @return
     */
    @Override
    public boolean isExistsMemberCard(Integer placeId, Integer cardTypeId, Integer uid) {
        TbBizPlaceMemberCardExample example = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andCardTypeIdEqualTo(cardTypeId);
        criteria.andMemberUidEqualTo(uid);
        criteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        List<TbBizPlaceMemberCard> placeMembers = tbBizPlaceMemberCardMapper.selectByExample(example);
        return (null != placeMembers && placeMembers.size() > 0);
    }

    /**
     * 根据手机号查询会员信息
     *
     * @param phone
     * @return
     */
    @Override
    public TbBizPlaceMember getPlaceMember(String phone) {
        TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
        TbBizPlaceMemberExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(phone).andIsDeleteEqualTo((byte)0).andStatusEqualTo((byte)1);//未删除,未注销
        List<TbBizPlaceMember> placeMembers = tbBizPlaceMemberMapper.selectByExample(example);
        if (null != placeMembers && placeMembers.size() > 0) {
            return placeMembers.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据uid查询会员信息
     *
     * @param memberUid
     * @return
     */
    @Override
    public TbBizPlaceMember getPlaceMemberByUid(Integer memberUid) {
        TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
        TbBizPlaceMemberExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(memberUid).andIsDeleteEqualTo((byte)0).andStatusEqualTo((byte)1);//未删除，未注销
        List<TbBizPlaceMember> placeMembers = tbBizPlaceMemberMapper.selectByExample(example);
        if (null != placeMembers && placeMembers.size() > 0) {
            return placeMembers.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据会员uid查询会员信息
     *
     * @param placeId
     * @return
     */
    public boolean isPlaceContainMemberCard(Integer placeId) {
        TbBizPlaceMemberCardTypeExample example = new TbBizPlaceMemberCardTypeExample();
        TbBizPlaceMemberCardTypeExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        //取消议价会员过滤限制
        //criteria.andSourceTypeEqualTo(Constants.BYTE_ONE);
        criteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_YES);
        List<TbBizPlaceMemberCardType> result = tbBizPlaceMemberCardTypeMapper.selectByExample(example);
        if (null != result && result.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据Id查询会员信息
     *
     * @param memberId
     * @return
     */
    @Override
    public TbBizPlaceMember getPlaceMemberById(Integer memberId) {
        return tbBizPlaceMemberMapper.selectByPrimaryKey(memberId);
    }

    /**
     * 获取用户会员卡明细
     *
     * @param reqMemberCardOperate
     * @return
     */
    public APIResponse<PageObj<List<RespMemberCardOperate>>> getMemberCardOperateDetail0(ReqMemberCardOperate reqMemberCardOperate) {
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        if (!StringUtils.isEmpty(reqMemberCardOperate.getPageNum())) {
            pageNum = reqMemberCardOperate.getPageNum();
        }
        if (!StringUtils.isEmpty(reqMemberCardOperate.getPageSize())) {
            pageSize = reqMemberCardOperate.getPageSize();
        }
        reqMemberCardOperate.setPageNum(pageNum);
        reqMemberCardOperate.setPageSize(pageSize);
        Integer placeId = reqMemberCardOperate.getPlaceId();
        String cardNumber = reqMemberCardOperate.getCardNumber();

        TbBizPlaceMemberOpHistoryExample example1 = new TbBizPlaceMemberOpHistoryExample();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria1 = example1.createCriteria();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria2 = example1.createCriteria();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria3 = example1.createCriteria();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria4 = example1.createCriteria();

        if (!StringUtils.isEmpty(placeId)) {
            criteria1.andPlaceIdEqualTo(placeId);
            criteria2.andPlaceIdEqualTo(placeId);
            criteria3.andPlaceIdEqualTo(placeId);
            criteria4.andPlaceIdEqualTo(placeId);
        }
        if (!StringUtils.isEmpty(cardNumber)) {
            criteria1.andInnerCardNoEqualTo(cardNumber);
            criteria2.andInnerCardNoEqualTo(cardNumber);
            criteria3.andInnerCardNoEqualTo(cardNumber);
            criteria4.andInnerCardNoEqualTo(cardNumber);
        }
        if (!StringUtils.isEmpty(reqMemberCardOperate.getStartDate()) && !StringUtils.isEmpty(reqMemberCardOperate.getEndDate())) {
            Date startDate = DateUtils.transferLongToDate(reqMemberCardOperate.getStartDate());
            Date endDate = DateUtils.transferLongToDate(reqMemberCardOperate.getEndDate());
            criteria1.andUpdateTimeBetween(startDate, endDate);
            criteria2.andUpdateTimeBetween(startDate, endDate);
            criteria3.andUpdateTimeBetween(startDate, endDate);
            criteria4.andUpdateTimeBetween(startDate, endDate);
        }
        String para = reqMemberCardOperate.getPara();
        if (!StringUtils.isEmpty(para)) {
            //手机后四位
            criteria1.andMobileLike("%" + para);
            //会员号
            criteria2.andInnerCardNoEqualTo(para);
            //姓名
            criteria3.andUserNameEqualTo(para);
            //订单号
            criteria4.andOrderNoEqualTo(para);
        }
        Integer operateType = reqMemberCardOperate.getOperateType();
        if (!StringUtils.isEmpty(operateType)) {
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN) {//开通会员
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER) {//消费
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND) {//退款
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST) {//调整
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME) {//调整有效期
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE) {//充值
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
            }
        }
        criteria1.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        criteria2.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        criteria3.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        criteria4.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        example1.or(criteria2);
        example1.or(criteria3);
        example1.or(criteria4);
        example1.setOrderByClause("id desc");
        int total = tbBizPlaceMemberOpHistoryMapper.countByExample(example1);
        example1.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbBizPlaceMemberOpHistory> list = tbBizPlaceMemberOpHistoryMapper.selectByExample(example1);
        List<RespMemberCardOperate> respMemberCardOperateList = this.tbMemberCardOperate2RespMemberCardOperate(list);
        PageObj<List<RespMemberCardOperate>> result = PageObj.create(total, pageNum, pageSize, respMemberCardOperateList);
        return APIResponse.returnSuccess(result);
    }

    public List<RespMemberCardOperate> getMemberCardOperateDetailExport(ReqMemberCardOperate reqMemberCardOperate) {

        if (!StringUtils.isEmpty(reqMemberCardOperate.getStartDate()) && !StringUtils.isEmpty(reqMemberCardOperate.getEndDate())) {
            String sdate = DateTimeUtils.convertDate2String("yyyy-MM-dd", new Date(reqMemberCardOperate.getStartDate())) + " 00:00:00";
            String edate = DateTimeUtils.convertDate2String("yyyy-MM-dd", new Date(reqMemberCardOperate.getEndDate())) + " 23:59:59";
            Date startDate = DateUtils.tranferStringToDate(sdate);
            Date endDate = DateUtils.tranferStringToDate(edate);
            reqMemberCardOperate.setDstartDate(startDate);
            reqMemberCardOperate.setDendDate(endDate);
        }

        if (!StringUtils.isEmpty(reqMemberCardOperate.getPlaceName())){
            reqMemberCardOperate.setPlaceName(reqMemberCardOperate.getPlaceName().trim());
        }
        if (!StringUtils.isEmpty(reqMemberCardOperate.getPlaceCode())){
            reqMemberCardOperate.setPlaceCode(reqMemberCardOperate.getPlaceCode().trim());
        }

        List<TbBizPlaceMemberOpHistoryVo> list = vPlaceMemberMapper.getTbBizPlaceMemberOpHistoryVos(reqMemberCardOperate);
        List<RespMemberCardOperate> respMemberCardOperateList = this.tbMemberCardOperateVo2RespMemberCardOperate(list);
        return respMemberCardOperateList;
    }


    public APIResponse<PageObj<List<RespMemberCardOperate>>> getMemberCardOperateDetail(ReqMemberCardOperate reqMemberCardOperate) {
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer oldPageNum = reqMemberCardOperate.getPageNum();
        if (!StringUtils.isEmpty(reqMemberCardOperate.getPageSize())) {
            pageSize = reqMemberCardOperate.getPageSize();
        }
        if (!StringUtils.isEmpty(reqMemberCardOperate.getPageNum())) {
            pageNum = reqMemberCardOperate.getPageNum() * pageSize;
            reqMemberCardOperate.setPageNum(pageNum);
        }
        if (!StringUtils.isEmpty(reqMemberCardOperate.getPlaceName())){
            reqMemberCardOperate.setPlaceName(reqMemberCardOperate.getPlaceName().trim());
        }
        if (!StringUtils.isEmpty(reqMemberCardOperate.getPlaceCode())){
            reqMemberCardOperate.setPlaceCode(reqMemberCardOperate.getPlaceCode().trim());
        }

        if (!StringUtils.isEmpty(reqMemberCardOperate.getStartDate()) && !StringUtils.isEmpty(reqMemberCardOperate.getEndDate())) {
            String sdate = DateTimeUtils.convertDate2String("yyyy-MM-dd", new Date(reqMemberCardOperate.getStartDate())) + " 00:00:00";
            String edate = DateTimeUtils.convertDate2String("yyyy-MM-dd", new Date(reqMemberCardOperate.getEndDate())) + " 23:59:59";
            Date startDate = DateUtils.tranferStringToDate(sdate);
            Date endDate = DateUtils.tranferStringToDate(edate);
            reqMemberCardOperate.setDstartDate(startDate);
            reqMemberCardOperate.setDendDate(endDate);
        }

        int total = vPlaceMemberMapper.countTbBizPlaceMemberOpHistoryVos(reqMemberCardOperate);
     /*   if (total == 0){
//            return APIResponse.returnFail(ApiResponseEnum.DO_NOT_HAVE_ANY_MORE_RECORD);
            return null;
        }*/

        List<TbBizPlaceMemberOpHistoryVo> list = vPlaceMemberMapper.getTbBizPlaceMemberOpHistoryVos(reqMemberCardOperate);
        List<RespMemberCardOperate> respMemberCardOperateList = this.tbMemberCardOperateVo2RespMemberCardOperate(list);
        PageObj<List<RespMemberCardOperate>> result = PageObj.create(total, oldPageNum, pageSize, respMemberCardOperateList);
        return APIResponse.returnSuccess(result);
    }

    List<RespMemberCardOperate> tbMemberCardOperateVo2RespMemberCardOperate(List<TbBizPlaceMemberOpHistoryVo> tbBizPlaceMemberOpHistoryList){
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)){
            List<RespMemberCardOperate> list = new ArrayList<>();
            Map map = new HashMap();
            for (TbBizPlaceMemberOpHistoryVo tbBizPlaceMemberOpHistory : tbBizPlaceMemberOpHistoryList){
                if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getInnerCardNo())){
                    TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
                    TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
                    tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(tbBizPlaceMemberOpHistory.getInnerCardNo());
                    List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
                    if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList)){
                        map.put(tbBizPlaceMemberOpHistory.getId(),tbBizPlaceMemberCardList.get(0).getCardType());
                    }
                }else if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getCardTypeId())){
                    TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(tbBizPlaceMemberOpHistory.getCardTypeId());
                    if (!StringUtils.isEmpty(tbBizPlaceMemberCardType)) {
                        map.put(tbBizPlaceMemberOpHistory.getId(), tbBizPlaceMemberCardType.getType());
                    }
                }
            }
            for (TbBizPlaceMemberOpHistoryVo tbBizPlaceMemberOpHistory : tbBizPlaceMemberOpHistoryList){
                RespMemberCardOperate respMemberCardOperate = new RespMemberCardOperate();
                respMemberCardOperate.setId(tbBizPlaceMemberOpHistory.getId());
                String userName = tbBizPlaceMemberOpHistory.getUserName();
                respMemberCardOperate.setCityId(tbBizPlaceMemberOpHistory.getCityId());
                respMemberCardOperate.setCityName(tbBizPlaceMemberOpHistory.getCityName());
                respMemberCardOperate.setPlaceName(tbBizPlaceMemberOpHistory.getPlaceName());
                respMemberCardOperate.setPlaceCode(tbBizPlaceMemberOpHistory.getPlaceCode());
                respMemberCardOperate.setPlaceId(tbBizPlaceMemberOpHistory.getPlaceId());
                respMemberCardOperate.setOrderNo(tbBizPlaceMemberOpHistory.getOrderNo());
                respMemberCardOperate.setNo(tbBizPlaceMemberOpHistory.getNo());

                respMemberCardOperate.setOpAfterAmount(tbBizPlaceMemberOpHistory.getOpAfterAmount());
                respMemberCardOperate.setOpAfterGiveAmount(tbBizPlaceMemberOpHistory.getOpAfterGiveAmount());
                respMemberCardOperate.setOpAfterNumbers(tbBizPlaceMemberOpHistory.getOpAfterNumbers());

                TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
                TbBizPlaceMemberExample.Criteria criteria = example.createCriteria();
                criteria.andUidEqualTo(tbBizPlaceMemberOpHistory.getUid());
                List<TbBizPlaceMember> tbBizPlaceMembers = null;
                respMemberCardOperate.setUserName(userName);
                String mobile =tbBizPlaceMemberOpHistory.getMobile();
                if (StringUtils.isEmpty(mobile)){
                    if (CollectionUtils.isNotEmpty(tbBizPlaceMembers)){
                        respMemberCardOperate.setPhone(tbBizPlaceMembers.get(0).getMobile());
                    }
                }else{
                    respMemberCardOperate.setPhone(mobile);
                }
                //备注
                if (tbBizPlaceMemberOpHistory.getSrc().intValue()==PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME){
                    if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getMemo())){
                        tbBizPlaceMemberOpHistory.setMemo("，"+tbBizPlaceMemberOpHistory.getMemo());
                    }
                    if (DateUtils.dateCompare(tbBizPlaceMemberOpHistory.getOpAfterDeadTime(),tbBizPlaceMemberOpHistory.getOpBeforeDeadTime(),false)){
                        tbBizPlaceMemberOpHistory.setMemo("增加"+tbBizPlaceMemberOpHistory.getOpMonth()+"个月"+tbBizPlaceMemberOpHistory.getMemo());
                    }else{
                        tbBizPlaceMemberOpHistory.setMemo("减少"+tbBizPlaceMemberOpHistory.getOpMonth()+"个月"+tbBizPlaceMemberOpHistory.getMemo());
                    }
                }
                respMemberCardOperate.setAmount(tbBizPlaceMemberOpHistory.getAmount());
                if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpAfterNumbers()) && !StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpBeforeNumbers())){
                    respMemberCardOperate.setNumber(tbBizPlaceMemberOpHistory.getOpAfterNumbers()-tbBizPlaceMemberOpHistory.getOpBeforeNumbers());
                }
                respMemberCardOperate.setMemberCardNo(tbBizPlaceMemberOpHistory.getInnerCardNo());
                respMemberCardOperate.setMemberCardTypeName(tbBizPlaceMemberOpHistory.getCardTypeName());
                respMemberCardOperate.setOperateType(tbBizPlaceMemberOpHistory.getSrc());
                respMemberCardOperate.setType(tbBizPlaceMemberOpHistory.getType().intValue());
                respMemberCardOperate.setUpdateTime(tbBizPlaceMemberOpHistory.getCreateTime());
                respMemberCardOperate.setMemo(tbBizPlaceMemberOpHistory.getMemo());
                respMemberCardOperate.setSrc(tbBizPlaceMemberOpHistory.getSrc().toString());
                respMemberCardOperate.setBusinessMode(tbBizPlaceMemberOpHistory.getBusinessMode());
                //1：APP，2：微信公众号，3：H5，4：商家端，5：小程序
                if (tbBizPlaceMemberOpHistory.getSourceType() != null && tbBizPlaceMemberOpHistory.getPlatform() != null){
                    if (tbBizPlaceMemberOpHistory.getSourceType().intValue() == 1
                            && tbBizPlaceMemberOpHistory.getPlatform().intValue() == 1 || tbBizPlaceMemberOpHistory.getPlatform().intValue() == 2){
                        respMemberCardOperate.setSourceType(PlaceConstants.PLACE_APP_PAY_TYPE);
                    }
                    if (tbBizPlaceMemberOpHistory.getSourceType().intValue() == 1
                            && tbBizPlaceMemberOpHistory.getPlatform().intValue() == 3){
                        respMemberCardOperate.setSourceType(PlaceConstants.PLACE_WX_PAY_TYPE);
                    }
                    if (tbBizPlaceMemberOpHistory.getSourceType().intValue() == 1
                            && tbBizPlaceMemberOpHistory.getPlatform().intValue() == 4 || tbBizPlaceMemberOpHistory.getPlatform().intValue() == 6){
                        respMemberCardOperate.setSourceType(PlaceConstants.PLACE_H5_PAY_TYPE);
                    }
                    if (tbBizPlaceMemberOpHistory.getSourceType().intValue() == 2
                            && tbBizPlaceMemberOpHistory.getPlatform().intValue() == 5){
                        respMemberCardOperate.setSourceType(PlaceConstants.PLACE_ADMIN_PAY_TYPE);
                    }
                    if (tbBizPlaceMemberOpHistory.getSourceType().intValue() == 1
                            && tbBizPlaceMemberOpHistory.getPlatform().intValue() == 7){
                        respMemberCardOperate.setSourceType(PlaceConstants.PLACE_WEAPP_PAY_TYPE);
                    }
                    if (StringUtils.isEmpty(respMemberCardOperate.getSourceType())){
                        respMemberCardOperate.setSourceType(PlaceConstants.PLACE_ADMIN_PAY_TYPE);
                    }
                } else {
                    respMemberCardOperate.setSourceType(PlaceConstants.PLACE_ADMIN_PAY_TYPE);
                }
//                respMemberCardOperate.setPayType(tbBizPlaceMemberOpHistory.getPayType());
                respMemberCardOperate.setPayType(tbBizPlaceMemberOpHistory.getAdminPayType());//修改为统一之后支付方式
                if (!StringUtils.isEmpty(map.get(tbBizPlaceMemberOpHistory.getId()))){
                    respMemberCardOperate.setCardType(Integer.parseInt(map.get(tbBizPlaceMemberOpHistory.getId()).toString()));
                }else{
                    System.out.println(tbBizPlaceMemberOpHistory.getId());
                }

                TbAdminUser tbAdminUser = tbAdminUserMapper.selectByPrimaryKey(tbBizPlaceMemberOpHistory.getCreateUid());
                if (!StringUtils.isEmpty(tbAdminUser)){
                    respMemberCardOperate.setOperateUserName(tbAdminUser.getTrueName());
                } else {
                    //线上操作人
                    APIResponse<RespUserInfoBase> userResponse = userServiceFacade.queryUserInfo(tbBizPlaceMemberOpHistory.getCreateUid());
                    if (userResponse.isRet()){
                        if (!StringUtils.isEmpty(userResponse.getData())){
                            if (!StringUtils.isEmpty(userResponse.getData().getNickName())){
                                respMemberCardOperate.setOperateUserName(userResponse.getData().getNickName());
                            }else{
                                respMemberCardOperate.setOperateUserName("未知");
                            }
                        }else{
                            respMemberCardOperate.setOperateUserName("未知");
                        }
                    }else{
                        respMemberCardOperate.setOperateUserName("未知");
                    }
                }
                list.add(respMemberCardOperate);
            }
            return list;
        }
        return null;
    }


    public List<RespMemberCardOperate> getMemberCardOperateDetailExport0(ReqMemberCardOperate reqMemberCardOperate) {
        Integer placeId = reqMemberCardOperate.getPlaceId();
        String cardNumber = reqMemberCardOperate.getCardNumber();

        TbBizPlaceMemberOpHistoryExample example1 = new TbBizPlaceMemberOpHistoryExample();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria1 = example1.createCriteria();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria2 = example1.createCriteria();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria3 = example1.createCriteria();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria4 = example1.createCriteria();

        if (!StringUtils.isEmpty(placeId)) {
            criteria1.andPlaceIdEqualTo(placeId);
            criteria2.andPlaceIdEqualTo(placeId);
            criteria3.andPlaceIdEqualTo(placeId);
            criteria4.andPlaceIdEqualTo(placeId);
        }
        if (!StringUtils.isEmpty(cardNumber)) {
            criteria1.andInnerCardNoEqualTo(cardNumber);
            criteria2.andInnerCardNoEqualTo(cardNumber);
            criteria3.andInnerCardNoEqualTo(cardNumber);
            criteria4.andInnerCardNoEqualTo(cardNumber);
        }
        if (!StringUtils.isEmpty(reqMemberCardOperate.getStartDate()) && !StringUtils.isEmpty(reqMemberCardOperate.getEndDate())) {
            Date startDate = DateUtils.transferLongToDate(reqMemberCardOperate.getStartDate());
            Date endDate = DateUtils.transferLongToDate(reqMemberCardOperate.getEndDate());
            criteria1.andUpdateTimeBetween(startDate, endDate);
            criteria2.andUpdateTimeBetween(startDate, endDate);
            criteria3.andUpdateTimeBetween(startDate, endDate);
            criteria4.andUpdateTimeBetween(startDate, endDate);
        }
        String para = reqMemberCardOperate.getPara();
        if (!StringUtils.isEmpty(para)) {
            //手机后四位
            criteria1.andMobileLike("%" + para);
            //会员号
            criteria2.andInnerCardNoEqualTo(para);
            //姓名
            criteria3.andUserNameEqualTo(para);
            //订单号
            criteria4.andOrderNoEqualTo(para);
        }
        Integer operateType = reqMemberCardOperate.getOperateType();
        if (!StringUtils.isEmpty(operateType)) {
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN) {//开通会员
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER) {//消费
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND) {//退款
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
            }
            if (operateType.intValue() == PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST) {//调整
                criteria1.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                criteria2.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                criteria3.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                criteria4.andSrcEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
            }
        }
        criteria1.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        criteria2.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        criteria3.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        criteria4.andStateEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        example1.or(criteria2);
        example1.or(criteria3);
        example1.or(criteria4);
        example1.setOrderByClause("id desc");
        List<TbBizPlaceMemberOpHistory> list = tbBizPlaceMemberOpHistoryMapper.selectByExample(example1);
        List<RespMemberCardOperate> respMemberCardOperateList = this.tbMemberCardOperate2RespMemberCardOperate(list);
        return respMemberCardOperateList;

    }

    /**
     * 统计会员卡数量
     *
     * @param keywords
     * @param placeId
     * @param cardType
     * @param status
     * @return
     */
    @Override
    public int countPlaceMemberCard(String keywords, Integer placeId, Integer cardType, Byte status,
                                    Integer cityId,
                                    String placeCode,
                                    String placeName,
                                    Byte orderType) {
        return vPlaceMemberMapper.countPlaceMemberCard(placeId, keywords, cardType, status, cityId, placeCode, placeName, orderType);
    }

    /**
     * 根据条件查询会员卡信息
     *
     * @param begin
     * @param pageSize
     * @param placeId
     * @param keywords
     * @param cardType
     * @param status
     * @return
     */
    @Override
    public List<RespMemberCardInfo> selectMemberCardList(Integer begin,
                                                         Integer pageSize,
                                                         Integer placeId,
                                                         String keywords,
                                                         Integer cardType,
                                                         Byte status,
                                                         Integer cityId,
                                                         String placeCode,
                                                         String placeName,
                                                         Byte orderType) {
        return vPlaceMemberMapper.selectMemberCardList(begin, pageSize, placeId, keywords, cardType, status, cityId, placeCode, placeName, orderType);
    }

    @Override
    public APIResponse<?> getMemberCardOperateDetailById(Integer id) {
        List<Object> list = new ArrayList<>();
        Map map = new HashMap();
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = tbBizPlaceMemberOpHistoryMapper.selectByPrimaryKey(id);
        //备注
        if (tbBizPlaceMemberOpHistory.getSrc().intValue()==PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME){
            if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getMemo())){
                tbBizPlaceMemberOpHistory.setMemo("，"+tbBizPlaceMemberOpHistory.getMemo());
            }
            if (DateUtils.dateCompare(tbBizPlaceMemberOpHistory.getOpAfterDeadTime(),tbBizPlaceMemberOpHistory.getOpBeforeDeadTime(),false)){
                tbBizPlaceMemberOpHistory.setMemo("增加"+tbBizPlaceMemberOpHistory.getOpMonth()+"个月"+tbBizPlaceMemberOpHistory.getMemo());
            }else{
                tbBizPlaceMemberOpHistory.setMemo("减少"+tbBizPlaceMemberOpHistory.getOpMonth()+"个月"+tbBizPlaceMemberOpHistory.getMemo());
            }
        }
        if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getInnerCardNo())){
            TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
            TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
            tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(tbBizPlaceMemberOpHistory.getInnerCardNo());
            List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
            map.put(tbBizPlaceMemberOpHistory.getId(),tbBizPlaceMemberCardList.get(0).getCardType());
        }else if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getCardTypeId())){
            TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(tbBizPlaceMemberOpHistory.getCardTypeId());
            map.put(tbBizPlaceMemberOpHistory.getId(),tbBizPlaceMemberCardType.getType());
        }
        list.add(map);
        list.add(tbBizPlaceMemberOpHistory);
        return APIResponse.returnSuccess(list);
    }

    /**
     * 冻结会员
     *
     * @param member
     * @return
     */
    @Override
    public APIResponse frozenMember(TbBizPlaceMember member) {
        if (null != member) {
            member.setStatus(PlaceConstants.PLACE_MEMBER_STATUS_FROZEN); // 会员冻结
            tbBizPlaceMemberMapper.updateByPrimaryKeySelective(member);
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("找不到会员");
        }

    }

    /**
     * 注销会员卡
     *
     * @param memberCard
     * @return
     */
    @Override
    public APIResponse logOffMemberCard(TbBizPlaceMemberCard memberCard) {
        if (null != memberCard) {
            memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_CANCEL);
            tbBizPlaceMemberCardMapper.updateByPrimaryKey(memberCard);
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 注销指定会员下所有会员卡
     *
     * @param member
     * @return
     */
    @Override
    public APIResponse logOffMemberCardByMember(TbBizPlaceMember member) {
        TbBizPlaceMemberCardExample example = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria criteria = example.createCriteria();
        criteria.andMemberUidEqualTo(member.getUid());
        List<TbBizPlaceMemberCard> cardList = tbBizPlaceMemberCardMapper.selectByExample(example);
        for (TbBizPlaceMemberCard memberCard : cardList) {
            memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_CANCEL);
            tbBizPlaceMemberCardMapper.updateByPrimaryKey(memberCard);
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 挂失会员卡
     *
     * @param memberCard
     * @return
     */
    @Override
    public APIResponse reportLossMemberCard(TbBizPlaceMemberCard memberCard) {
        if (null != memberCard) {
            memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_LOSS);
            tbBizPlaceMemberCardMapper.updateByPrimaryKey(memberCard);
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 根据场馆id获取会员类型
     *
     * @param placeId
     * @return
     */
    @Override
    public List<TbBizPlaceMemberCardType> getMemberTypeByPlaceId(Integer placeId) {
        TbBizPlaceMemberCardTypeExample example = new TbBizPlaceMemberCardTypeExample();
        TbBizPlaceMemberCardTypeExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_YES);
        List<TbBizPlaceMemberCardType> list = tbBizPlaceMemberCardTypeMapper.selectByExample(example);
        return list;
    }

    /**
     * 更新会员卡
     *
     * @param memberCard
     */
    @Override
    public void updatePlaceMemberCard(TbBizPlaceMemberCard memberCard) {
        tbBizPlaceMemberCardMapper.updateByPrimaryKeySelective(memberCard);
    }

    /**
     * 更新会员信息
     *
     * @param member
     */
    @Override
    public void updatePlaceMember(TbBizPlaceMember member) {
        tbBizPlaceMemberMapper.updateByPrimaryKeySelective(member);
    }

    /**
     * 增加会员消费记录
     *
     * @param opHistory
     */
    @Override
    public void addPlaceMemberCardOpRecord(TbBizPlaceMemberOpHistory opHistory) {
        tbBizPlaceMemberOpHistoryMapper.insertSelective(opHistory);
    }

    public APIResponse getMemberTypeNameByPlaceId(Integer placeId) {
        if (!StringUtils.isEmpty(placeId)) {
            TbBizPlaceMemberCardTypeExample example = new TbBizPlaceMemberCardTypeExample();
            TbBizPlaceMemberCardTypeExample.Criteria criteria = example.createCriteria();
            criteria.andPlaceIdEqualTo(placeId);
            criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);//未删除
            criteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_YES);//启用
            List<TbBizPlaceMemberCardType> tbBizPlaceMemberCardTypeList = tbBizPlaceMemberCardTypeMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(tbBizPlaceMemberCardTypeList)) {
                return APIResponse.returnFail("此场馆没有会员类型");
            } else {
                Map map = new HashMap();
                for (TbBizPlaceMemberCardType tbBizPlaceMemberCardType : tbBizPlaceMemberCardTypeList) {
                    map.put(tbBizPlaceMemberCardType.getId(), tbBizPlaceMemberCardType.getName());
                }
                return APIResponse.returnSuccess(map);
            }
        }
        return APIResponse.returnFail("placeId must input");
    }

    /**
     * 根据type获取字典类型
     *
     * @param type
     * @return
     */
    public Map<String, String> getDictDisplayName(String type) {
        HashMap<String, String> map = new HashMap<String, String>();
        DictExample dictExample = new DictExample();
        DictExample.Criteria dictCriteria = dictExample.createCriteria();
        dictCriteria.andTagGroupEqualTo(type);
        List<Dict> result = dictMapper.selectDataValueByExample(dictExample);
        for (Dict dict : result) {
            map.put(dict.getDataKey(), dict.getDataValue());
        }
        return map;
    }

    /**
     * 会员卡类型转化返回请求类型
     *
     * @param tbBizPlaceMemberCardTypeList
     * @return
     */
    public List<RespMemberCardType> tbMemberCardType2RespMemberCardType(List<TbBizPlaceMemberCardType> tbBizPlaceMemberCardTypeList) {
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardTypeList)) {
            List<RespMemberCardType> list = new ArrayList<>();
            Map<String, String> map = getDictDisplayName(PlaceConstants.PLACE_MEMBER_CARD_TYPE);
            for (TbBizPlaceMemberCardType tbBizPlaceMemberCardType : tbBizPlaceMemberCardTypeList) {
                RespMemberCardType respMemberCardType = new RespMemberCardType();
                BeanUtils.copyProperties(tbBizPlaceMemberCardType, respMemberCardType);
                if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getPlaceId())) {
                    TbBizPlace basePlace = placeMapper.selectByPrimaryKey(tbBizPlaceMemberCardType.getPlaceId());
                    if (!StringUtils.isEmpty(basePlace)) {
                        respMemberCardType.setPlaceName(basePlace.getName());//Todo 待优化
                        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getType())) {
                            respMemberCardType.setMemberType(MapUtils.getString(map, tbBizPlaceMemberCardType.getType().toString()));
                        }
                        respMemberCardType.setCategoryIds(JSON.parseObject(tbBizPlaceMemberCardType.getCategoryIds(), List.class));
                    }
                }
                //判断会员卡类型是否可用
                respMemberCardType.setIsUse(isMemberCardTypeUse(tbBizPlaceMemberCardType.getId(),
                        tbBizPlaceMemberCardType.getType(),tbBizPlaceMemberCardType.getPlaceId()));

                //开始时间
                respMemberCardType.setAvailableStartTime(DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCardType.getAvailableStartTime()));
                // 结束时间
                respMemberCardType.setAvailableEndTime(DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCardType.getAvailableEndTime()));
                // 增加人次
                TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
                tbBizPlaceMemberCardExample.createCriteria().andCardTypeIdEqualTo(tbBizPlaceMemberCardType.getId());
                Integer passengers = this.tbBizPlaceMemberCardMapper.countByExample(tbBizPlaceMemberCardExample);
                respMemberCardType.setPassengers(passengers);
                list.add(respMemberCardType);
            }
            return list;
        }
        return null;
    }


    /**
     *判断会员卡类型是否可用
     * @param cardId 会员卡类型主键
     * @param cardTypeId 会员卡类型 次卡 储值卡，折扣卡，储值折扣卡等
     * @param placeId
     * @return
     */
    private Byte isMemberCardTypeUse(Integer cardId,Byte cardTypeId,Integer placeId){
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andCardTypeIdEqualTo(cardId);
        tbBizPlaceMemberCardCriteria.andCardTypeEqualTo(cardTypeId);
        tbBizPlaceMemberCardCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceMemberCard> placeMemberCards = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
        if (null != placeMemberCards && placeMemberCards.size()>0){
            return (byte)1;
        }
        return (byte)0;
    }
    public List<RespMemberCardOperate> tbMemberCardOperate2RespMemberCardOperate(List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList){
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)){
            List<RespMemberCardOperate> list = new ArrayList<>();
            Map map = new HashMap();
            for (TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory : tbBizPlaceMemberOpHistoryList){
                if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getInnerCardNo())){
                    TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
                    TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
                    tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(tbBizPlaceMemberOpHistory.getInnerCardNo());
                    List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
                    if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList)){
                        map.put(tbBizPlaceMemberOpHistory.getId(),tbBizPlaceMemberCardList.get(0).getCardType());
                    }
                }else if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getCardTypeId())){
                    TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(tbBizPlaceMemberOpHistory.getCardTypeId());
                    if (!StringUtils.isEmpty(tbBizPlaceMemberCardType)) {
                        map.put(tbBizPlaceMemberOpHistory.getId(), tbBizPlaceMemberCardType.getType());
                    }
                }
            }
            for (TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory : tbBizPlaceMemberOpHistoryList){
                RespMemberCardOperate respMemberCardOperate = new RespMemberCardOperate();
                respMemberCardOperate.setId(tbBizPlaceMemberOpHistory.getId());
                String userName = tbBizPlaceMemberOpHistory.getUserName();

                TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
                TbBizPlaceMemberExample.Criteria criteria = example.createCriteria();
                criteria.andUidEqualTo(tbBizPlaceMemberOpHistory.getUid());
                List<TbBizPlaceMember> tbBizPlaceMembers = null;
                respMemberCardOperate.setUserName(userName);
                String mobile =tbBizPlaceMemberOpHistory.getMobile();
                if (StringUtils.isEmpty(mobile)){
                    if (CollectionUtils.isNotEmpty(tbBizPlaceMembers)){
                        respMemberCardOperate.setPhone(tbBizPlaceMembers.get(0).getMobile());
                    }
                }else{
                    respMemberCardOperate.setPhone(mobile);
                }
                //备注
                if (tbBizPlaceMemberOpHistory.getSrc().intValue()==PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME){
                    if (DateUtils.dateCompare(tbBizPlaceMemberOpHistory.getOpAfterDeadTime(),tbBizPlaceMemberOpHistory.getOpBeforeDeadTime(),false)){
                        tbBizPlaceMemberOpHistory.setMemo("增加"+tbBizPlaceMemberOpHistory.getOpMonth()+"个月，"+tbBizPlaceMemberOpHistory.getMemo());
                    }else{
                        tbBizPlaceMemberOpHistory.setMemo("减少"+tbBizPlaceMemberOpHistory.getOpMonth()+"个月，"+tbBizPlaceMemberOpHistory.getMemo());
                    }
                }
                respMemberCardOperate.setAmount(tbBizPlaceMemberOpHistory.getAmount());
                if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpAfterNumbers()) && !StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpBeforeNumbers())){
                    respMemberCardOperate.setNumber(tbBizPlaceMemberOpHistory.getOpAfterNumbers()-tbBizPlaceMemberOpHistory.getOpBeforeNumbers());
                }
                respMemberCardOperate.setMemberCardNo(tbBizPlaceMemberOpHistory.getInnerCardNo());
                respMemberCardOperate.setMemberCardTypeName(tbBizPlaceMemberOpHistory.getCardTypeName());
                respMemberCardOperate.setOperateType(tbBizPlaceMemberOpHistory.getSrc());
                respMemberCardOperate.setType(tbBizPlaceMemberOpHistory.getType().intValue());
                respMemberCardOperate.setUpdateTime(tbBizPlaceMemberOpHistory.getCreateTime());
                respMemberCardOperate.setMemo(tbBizPlaceMemberOpHistory.getMemo());
                respMemberCardOperate.setSrc(tbBizPlaceMemberOpHistory.getSrc().toString());
                respMemberCardOperate.setBusinessMode(tbBizPlaceMemberOpHistory.getBusinessMode());
                if (!StringUtils.isEmpty(map.get(tbBizPlaceMemberOpHistory.getId()))){
                    respMemberCardOperate.setCardType(Integer.parseInt(map.get(tbBizPlaceMemberOpHistory.getId()).toString()));
                }else{
                    System.out.println(tbBizPlaceMemberOpHistory.getId());
                }

                TbAdminUser tbAdminUser = tbAdminUserMapper.selectByPrimaryKey(tbBizPlaceMemberOpHistory.getCreateUid());
                if (!StringUtils.isEmpty(tbAdminUser)){
                    respMemberCardOperate.setOperateUserName(tbAdminUser.getTrueName());
                } else {
                    //线上操作人
                    APIResponse<RespUserInfoBase> userResponse = userServiceFacade.queryUserInfo(tbBizPlaceMemberOpHistory.getCreateUid());
                    if (userResponse.isRet()){
                        if (!StringUtils.isEmpty(userResponse.getData())){
                            if (!StringUtils.isEmpty(userResponse.getData().getNickName())){
                                respMemberCardOperate.setOperateUserName(userResponse.getData().getNickName());
                            }else{
                                respMemberCardOperate.setOperateUserName("未知");
                            }
                        }else{
                            respMemberCardOperate.setOperateUserName("未知");
                        }
                    }else{
                        respMemberCardOperate.setOperateUserName("未知");
                    }
                }
                list.add(respMemberCardOperate);
            }
            return list;
        }
        return null;
    }

    @Override
    public TbBizPlaceMemberCard getPlaceMemberCardInfo(String cardNo, Integer placeId, Integer uid) {
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(cardNo);
        if (null != placeId) {
            List<Integer> placeIdList = new ArrayList<Integer>();
            // 通馆会员做特殊处理
            if (checkIsShareVip(placeId)){
                placeIdList = this.getShareVipPlaceIds(placeId);
            }
            if (null != placeIdList && placeIdList.size() > 1){
                tbBizPlaceMemberCardCriteria.andPlaceIdIn(placeIdList);
            } else {
                tbBizPlaceMemberCardCriteria.andPlaceIdEqualTo(placeId);
            }
        }
        if (null != uid) {
            tbBizPlaceMemberCardCriteria.andMemberUidEqualTo(uid);
        }
        //tbBizPlaceMemberCardCriteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        tbBizPlaceMemberCardExample.setOrderByClause("id for update");//利用这种方式可以在查询余额时加上排它锁，解决并发操作余额问题
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList)) {
            return tbBizPlaceMemberCardList.get(0);
        }
        return null;
    }

    @Override
    public int updatePlaceMemberCardInfo(TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample, TbBizPlaceMemberCard tbBizPlaceMemberCard) {
        return tbBizPlaceMemberCardMapper.updateByExampleSelective(tbBizPlaceMemberCard, tbBizPlaceMemberCardExample);
    }


    /*
    会员统计
     */
    @Override
    public APIResponse getMemberStatisticsByPlaceId(ReqMemberCardOperate reqMemberCardOperate) {
        Integer pageNum = reqMemberCardOperate.getPageNum();
        Integer pageSize = reqMemberCardOperate.getPageSize();
        int total = vPlaceMemberMapper.getCardIdCountPlaceId(reqMemberCardOperate);
        reqMemberCardOperate.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<RespMemberCardOperate> cardTypeIdList = vPlaceMemberMapper.getCardIdPlaceId(reqMemberCardOperate);
        BigDecimal totalRechargeAmount = new BigDecimal(0);
        BigDecimal totalConsumeAmount = new BigDecimal(0);
        BigDecimal totalAdjustAmount = new BigDecimal(0);
        Integer totalConsumeCount = 0;
        Integer totalAdjustCount = 0;
        RespMemberCardOperate voVal = new RespMemberCardOperate();

        List<RespMemberCardOperate> respList = new ArrayList<>();
        for (RespMemberCardOperate vo : cardTypeIdList) {
            ReqMemberCardOperate req = new ReqMemberCardOperate();
            req.setCardTypeId(vo.getCardTypeId());
            req.setStartTime(reqMemberCardOperate.getStartTime());
            req.setEndTime(reqMemberCardOperate.getEndTime());
            RespMemberCardOperate respVo = new RespMemberCardOperate();
            int newCardCount = vPlaceMemberMapper.getNewCardCount(req); //新增开卡数
            respVo.setNewCardCount(newCardCount);
            respVo.setCardName(vo.getCardName());
            if (PlaceConstants.PLACE_MEMBER_CARD.equals(vo.getCardType())) {
                //调整次卡次数
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPCARDCOUNT);
                RespMemberCardOperate opcardCount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (opcardCount != null) {
                    respVo.setTotalAdjustCount(opcardCount.getOpCardCount());
                }
                //次卡消费次数
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                RespMemberCardOperate consumeAmount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (consumeAmount != null) {
                    respVo.setTotalConsumeCount(consumeAmount.getOpCardCount());
                }
            } else {
                //充值总金额
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
                RespMemberCardOperate reChargeAmount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (reChargeAmount != null) {
                    respVo.setTotalRechargeAmount(reChargeAmount.getAmount());
                }
                //消费总金额
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                RespMemberCardOperate consumeAmont = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (consumeAmont != null) {
                    respVo.setTotalConsumeAmount(consumeAmont.getAmount());
                }
                //余额调整
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                RespMemberCardOperate adjustAmount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (adjustAmount != null) {
                    respVo.setTotalAdjustAmount(adjustAmount.getAmount());
                }
            }
            respList.add(respVo);
        }
        voVal.setList(respList);
        PageObj<List<RespMemberCardOperate>> result = PageObj.create(total, pageNum, pageSize, respList);
        return APIResponse.returnSuccess(result);


    }

    @Override
    public APIResponse getMemberTotalDataByPlaceId(ReqMemberCardOperate reqMemberCardOperate) {
        RespMemberCardOperate voVal = new RespMemberCardOperate();
        //会员总数
        int memberCount = this.countPlaceMemberCard(null, reqMemberCardOperate.getPlaceId(), null, null, null, null, null, null);
        voVal.setMemberCount(memberCount);
        //会员总余额
        RespMemberCardOperate val = vPlaceMemberMapper.getCardAmount(reqMemberCardOperate.getPlaceId(), 0);
        if (val != null) {
            BigDecimal totalAmount = val.getSurplusAmount().add(val.getSurplusGiveAmount());
            voVal.setTotalAmount(totalAmount);
        }
        //次卡剩余次数
        RespMemberCardOperate cardVo = vPlaceMemberMapper.getCardNumbers(PlaceConstants.PLACE_MEMBER_CARD, reqMemberCardOperate.getPlaceId(), 0);
        if (cardVo != null) {
            int freqCardNum = cardVo.getSurplusNumbers();
            voVal.setSurplusNumbers(freqCardNum);
        }
        return APIResponse.returnSuccess(voVal);
    }


    /*
  会员统计导出
   */
    @Override
    public APIResponse exportMemberStatisticsByPlaceId(ReqMemberCardOperate reqMemberCardOperate) {
        List<RespMemberCardOperate> cardTypeIdList = vPlaceMemberMapper.getCardIdPlaceId(reqMemberCardOperate);
        BigDecimal totalRechargeAmount = new BigDecimal(0);
        BigDecimal totalConsumeAmount = new BigDecimal(0);
        BigDecimal totalAdjustAmount = new BigDecimal(0);
        Integer totalConsumeCount = 0;
        Integer totalAdjustCount = 0;
        RespMemberCardOperate voVal = new RespMemberCardOperate();
        List<RespMemberCardOperate> respList = new ArrayList<>();
        for (RespMemberCardOperate vo : cardTypeIdList) {
            ReqMemberCardOperate req = new ReqMemberCardOperate();
            req.setCardTypeId(vo.getCardTypeId());
            req.setStartTime(reqMemberCardOperate.getStartTime());
            req.setEndTime(reqMemberCardOperate.getEndTime());
            RespMemberCardOperate respVo = new RespMemberCardOperate();
            int newCardCount = vPlaceMemberMapper.getNewCardCount(req); //新增开卡数
            respVo.setNewCardCount(newCardCount);
            respVo.setCardName(vo.getCardName());
            if (PlaceConstants.PLACE_MEMBER_CARD.equals(vo.getCardType())) {
                //调整次卡次数
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPCARDCOUNT);
                RespMemberCardOperate opcardCount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (opcardCount != null) {
                    respVo.setTotalAdjustCount(opcardCount.getOpCardCount());
                }
                //次卡消费次数
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                RespMemberCardOperate consumeAmount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (consumeAmount != null) {
                    respVo.setTotalConsumeCount(consumeAmount.getOpCardCount());
                }
            } else {
                //充值总金额
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
                RespMemberCardOperate reChargeAmount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (reChargeAmount != null) {
                    respVo.setTotalRechargeAmount(reChargeAmount.getAmount());
                }
                //消费总金额
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                RespMemberCardOperate consumeAmont = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (consumeAmont != null) {
                    respVo.setTotalConsumeAmount(consumeAmont.getAmount());
                }
                //余额调整
                req.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
                RespMemberCardOperate adjustAmount = vPlaceMemberMapper.getMemberStatisticsByPlaceId(req);
                if (adjustAmount != null) {
                    respVo.setTotalAdjustAmount(adjustAmount.getAmount());
                }
            }
            respList.add(respVo);
        }
        voVal.setList(respList);
        return APIResponse.returnSuccess(voVal);


    }

    /**
     * 获取场馆会员卡类型
     *
     * @param placeId
     * @param isContainDisabled
     * @return
     */
    @Override
    public List<TbBizPlaceMemberCardType> getMemberCardTypeListByPlaceId(Integer placeId, boolean isContainDisabled) {
        TbBizPlaceMemberCardTypeExample example = new TbBizPlaceMemberCardTypeExample();
        TbBizPlaceMemberCardTypeExample.Criteria criteria = example.createCriteria();
        if (null != placeId) {
            criteria.andPlaceIdEqualTo(placeId);
        }
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);//未删除
        criteria.andSourceTypeEqualTo(PlaceConstants.PLACE_MEMBER); // 客户端会员卡列表只展示普通会员卡，过滤议价会员卡
        if (isContainDisabled) {
            criteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_YES);//启用
        }
        example.setOrderByClause(" create_time desc");
        List<TbBizPlaceMemberCardType> result = tbBizPlaceMemberCardTypeMapper.selectByExample(example);
        return result;
    }


    @Override
    public TbBizPlaceMemberCard getCardInfoByMemberCardId(Integer memberCardId) {
        return tbBizPlaceMemberCardMapper.selectByPrimaryKey(memberCardId);
    }

    @Override
    public int savePlaceMemberOpHistory(TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory) {
        return tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
    }

    @Override
    public List<TbBizPlaceMemberOpHistory> getMinDeadLineTimeByInnerCard(String innerCardNo) {
        TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
        TbBizPlaceMemberOpHistoryExample.Criteria tbBizPlaceMemberOpHistoryCriteria = tbBizPlaceMemberOpHistoryExample.createCriteria();
        tbBizPlaceMemberOpHistoryCriteria.andInnerCardNoEqualTo(innerCardNo);
        tbBizPlaceMemberOpHistoryCriteria.andOpBeforeDeadTimeIsNotNull();
        tbBizPlaceMemberOpHistoryExample.setOrderByClause("op_before_dead_time ASC ");
        List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = tbBizPlaceMemberOpHistoryMapper.selectByExample(tbBizPlaceMemberOpHistoryExample);
        return tbBizPlaceMemberOpHistoryList;
    }

    /**
     * 根据手机号或电话模糊匹配会员信息 //todo:如果前端分页放开注释和注释掉中间部分
     */
    @Override
    public APIResponse<?> queryPlaceMemberByPhoneOrName(Integer placeId, String phoneOrName) {
        List<Integer> placeIdList = new ArrayList<Integer>();
        // 通馆做特殊处理
        if (checkIsShareVip(placeId)){
            placeIdList = this.getShareVipPlaceIds(placeId);
        }
        ReqPlaceMemberSearch reqMemberSearch = new ReqPlaceMemberSearch();
        reqMemberSearch.setKey(phoneOrName);
        reqMemberSearch.setPlaceId(placeId);
        reqMemberSearch.setPlaceIdList(placeIdList);
        return APIResponse.returnSuccess(vPlaceMemberMapper.queryPlaceMemberByCondition(reqMemberSearch));
        
//        TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
//        TbBizPlaceMemberExample.Criteria criteria1 = example.createCriteria();
//        TbBizPlaceMemberExample.Criteria criteria2 = example.createCriteria();
//        if (StringUtils.isEmpty(phoneOrName)) {
//            APIResponse.returnFail("参数不能为空！");
//        }
//        criteria1.andMobileLike("%" + phoneOrName + "%");
//        criteria2.andUserNameLike("%" + phoneOrName + "%");
//        example.or(criteria2);
//        List<TbBizPlaceMember> placeMembers = tbBizPlaceMemberMapper.selectByExample(example);
//        /*int total = tbBizPlaceMemberMapper.countByExample(example);
//        example.setPage(new Page(pageNum * pageSize, pageSize, total));*/
//        if (null != placeMembers && placeMembers.size() > 0) {
//            List<Integer> memberUid = Lists.newArrayList();
//            for (TbBizPlaceMember tbBizPlaceMember : placeMembers) {
//                memberUid.add(tbBizPlaceMember.getUid());
//            }
//            TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
//            TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
//            tbBizPlaceMemberCardCriteria.andMemberUidIn(memberUid);
//
//            if (null != placeIdList && placeIdList.size() > 1){
//                tbBizPlaceMemberCardCriteria.andPlaceIdIn(placeIdList);
//            } else {
//                tbBizPlaceMemberCardCriteria.andPlaceIdEqualTo(placeId);
//            }
//            tbBizPlaceMemberCardCriteria.andStatusEqualTo(PlaceConstants.YES);
//            List<TbBizPlaceMemberCard> placeMemberCards = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
//            if (CollectionUtils.isEmpty(placeMemberCards)) {
//                return APIResponse.returnSuccess(null);
//            }
//            memberUid.clear();
//            for (TbBizPlaceMemberCard tbBizPlaceMemberCard : placeMemberCards) {
//                memberUid.add(tbBizPlaceMemberCard.getMemberUid());
//            }
//            TbBizPlaceMemberExample tbBizPlaceMemberExample = new TbBizPlaceMemberExample();
//            TbBizPlaceMemberExample.Criteria tbBizPlaceMemberCriteria = tbBizPlaceMemberExample.createCriteria();
//            tbBizPlaceMemberCriteria.andUidIn(memberUid);
//            List<TbBizPlaceMember> placeMembersForPlace = tbBizPlaceMemberMapper.selectByExample(tbBizPlaceMemberExample);
//            return APIResponse.returnSuccess(placeMembersForPlace);
//        } else {
//            return APIResponse.returnSuccess(null);
//        }
        /*return APIResponse.returnSuccess(placeMembers);*/
    }

    @Override
    public APIResponse<?> showCardRecharge(Integer cardID,Integer placeId) {
        return vaildCardByID(cardID,placeId);
    }

    @Override
    public APIResponse<?> getVipPayDetail(Integer placeId, Integer cardTypeId) {
        TbBizPlaceMemberCardTypeExample tbBizPlaceMemberCardTypeExample = new TbBizPlaceMemberCardTypeExample();
        tbBizPlaceMemberCardTypeExample.createCriteria().andIdEqualTo(cardTypeId).andPlaceIdEqualTo(placeId);
        List<TbBizPlaceMemberCardType> tbBizPlaceMemberCardTypes =
                tbBizPlaceMemberCardTypeMapper.selectByExample(tbBizPlaceMemberCardTypeExample);
        if (CollectionUtils.isEmpty(tbBizPlaceMemberCardTypes)) {
            return APIResponse.returnFail("没有此类型的会员卡");
        }
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypes.get(0);
        return APIResponse.returnSuccess(tbBizPlaceMemberCardType);
    }

    @Override
    public List<TbBizPlaceMemberCard> getTbBizPlaceMemberCardsByUid(Integer uid) {
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        tbBizPlaceMemberCardExample.createCriteria().andMemberUidEqualTo(uid)
                .andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL)
                .andDeadLineTimeGreaterThanOrEqualTo(new Date());

        //按照开卡时间降序排序
        tbBizPlaceMemberCardExample.setOrderByClause(" create_time desc");
        
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCards =
                tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);

        return tbBizPlaceMemberCards;
    }

    @Override
    public APIResponse<List<RespPlaceMemberCardDetail>> getRespPlaceMemberCardDetail(Map<Integer, List<TbBizPlaceMemberCard>> map) {
        List<RespPlaceMemberCardDetail> respPlaceMemberCardDetails = new ArrayList<>();
        for (Map.Entry<Integer, List<TbBizPlaceMemberCard>> entry : map.entrySet()) {
            Integer placeId = entry.getKey();
            TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeId);
            if (StringUtils.isEmpty(tbBizPlace)) {
                return APIResponse.returnFail("没有此场馆信息");
            }

            List<TbBizPlaceMemberCard> tbBizPlaceMemberCards = entry.getValue();
            for (TbBizPlaceMemberCard tbBizPlaceMemberCard : tbBizPlaceMemberCards) {
                RespPlaceMemberCardDetail respPlaceMemberCardDetail = new RespPlaceMemberCardDetail();
                respPlaceMemberCardDetail.setVenueName(tbBizPlace.getName());
                respPlaceMemberCardDetail.setVipNo(tbBizPlaceMemberCard.getInnerCardNo());
                respPlaceMemberCardDetail.setCreateTime(tbBizPlaceMemberCard.getCreateTime());
                // 余额
                if (null == tbBizPlaceMemberCard.getSurplusGiveAmount()){
                    // 赠送余额为空
                    respPlaceMemberCardDetail.setBalance(tbBizPlaceMemberCard.getSurplusAmount());
                } else {
                    respPlaceMemberCardDetail.setBalance(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()));
                }
                respPlaceMemberCardDetail.setNumbers(tbBizPlaceMemberCard.getSurplusNumbers()); // 剩余次数
                RespMemberCardType respMemberCardType = new RespMemberCardType();
                TbBizPlaceMemberCardType tbBizPlaceMemberCardType =
                        this.tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(tbBizPlaceMemberCard.getCardTypeId());
                if (StringUtils.isEmpty(tbBizPlaceMemberCardType)) {
                    return APIResponse.returnFail("没有此类型的会员卡类型");
                }
                respMemberCardType.setId(tbBizPlaceMemberCardType.getId());
                respMemberCardType.setName(tbBizPlaceMemberCardType.getName());
                respMemberCardType.setDescription(tbBizPlaceMemberCardType.getDescription());
                respMemberCardType.setType(tbBizPlaceMemberCardType.getType());
                respMemberCardType.setInitAmount(tbBizPlaceMemberCardType.getInitAmount());
                respMemberCardType.setGiveAmount(tbBizPlaceMemberCardType.getGiveAmount());
                respMemberCardType.setDiscount(tbBizPlaceMemberCardType.getDiscount());
                respMemberCardType.setFrequency(tbBizPlaceMemberCardType.getFrequency());
                respMemberCardType.setCategoryNameStr(tbBizPlaceMemberCardType.getCategoryIds());
                respMemberCardType.setStatus(tbBizPlaceMemberCardType.getStatus());
                respPlaceMemberCardDetail.setVipDetail(respMemberCardType);
                respPlaceMemberCardDetails.add(respPlaceMemberCardDetail);
            }
        }
        //对会员按照创建时间降排序
        if (!CollectionUtils.isEmpty(respPlaceMemberCardDetails)) {
        	Collections.sort(respPlaceMemberCardDetails, new Comparator<RespPlaceMemberCardDetail>() {
				@Override
				public int compare(RespPlaceMemberCardDetail o1, RespPlaceMemberCardDetail o2) {
					return o2.getCreateTime().compareTo(o1.getCreateTime());
				}
			});
        	
        }
        return APIResponse.returnSuccess(respPlaceMemberCardDetails);
    }
    

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    public APIResponse<?> buyVenueVip(Integer userId, TbBizPlaceMemberCardType tbBizPlaceMemberCardType,
                                      Integer payTypeId, Integer platformType,Integer refereesId, Integer larkAppId) {
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceMemberCardType.getPlaceId());
        if (StringUtils.isEmpty(tbBizPlace)) {
            return APIResponse.returnFail("没有相关场馆信息");
        }
        // 判断用户是否为会员
        APIResponse<RespUserInfoBase> respUserInfoBaseAPIResponse = this.userServiceFacade.queryUserInfo(userId);
        if (!respUserInfoBaseAPIResponse.isRet()) {
            return respUserInfoBaseAPIResponse;
        }
        TbBizPlaceMemberExample tbBizPlaceMemberExample = new TbBizPlaceMemberExample();
        tbBizPlaceMemberExample.createCriteria().andUidEqualTo(userId);
        List<TbBizPlaceMember> tbBizPlaceMembers = this.tbBizPlaceMemberMapper.selectByExample(tbBizPlaceMemberExample);
        TbBizPlaceMember tbBizPlaceMember = new TbBizPlaceMember();

        if (CollectionUtils.isEmpty(tbBizPlaceMembers)) {
            RespUserInfoBase respUserInfoBase = respUserInfoBaseAPIResponse.getData();
            if (!StringUtils.isEmpty(respUserInfoBase.getGender())) {
                tbBizPlaceMember.setGender(respUserInfoBase.getGender().byteValue());
            }
            tbBizPlaceMember.setUserName(!StringUtils.isEmpty(respUserInfoBase.getRealName())
                    ? respUserInfoBase.getRealName() : respUserInfoBase.getNickName());
            tbBizPlaceMember.setMobile(respUserInfoBase.getMobile());
            tbBizPlaceMember.setType((byte) 1); // 1场馆会员
            tbBizPlaceMember.setMemo("新增会员");
            tbBizPlaceMember.setStatus(PlaceConstants.PLACE_MEMBER_STATUS_FROZEN);
            tbBizPlaceMember.setUid(respUserInfoBase.getUid());
            tbBizPlaceMemberMapper.insertSelective(tbBizPlaceMember);
        }else{
            tbBizPlaceMember = tbBizPlaceMembers.get(0);
        }
        // 支付会员卡
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        String ver = httpServletRequest.getHeader("APPVersion");

        // 获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, userId);
        //// TODO: 16/11/14 测试用
//        strPlatform = "2";
//        ver = "2.1.1-DEBUG";

        //设置回调方式
        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_ORDER_CALLBACK_TYPE.getCode());
        Integer callbackType = 0;
        if (parameter != null && parameter.getParameterValue() != null) {
            callbackType = Integer.valueOf(parameter.getParameterValue());
        }
        //调用订单系统，获取预支付信息
        com.quanyan.api.APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new com.quanyan.api.APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();
        reqOrderSaveAPIRequest.setData(reqOrderSave);
        reqOrderSave.setSourceBusinessId(Constants.PLACE_TICKET_CODE);
        reqOrderSave.setSourceSystemId(Constants.PLACE_SYSTEM_CODE);
        reqOrderSave.setPlatformType(platformType);//设置平台类型
        reqOrderSave.setContactMobile(tbBizPlaceMember.getMobile());
        reqOrderSave.setContactName(tbBizPlaceMember.getUserName());
        reqOrderSave.setExtraParam("");
        if (tbBizPlace.getCityId() != null && tbBizPlace.getCityId().equals(3)) {
            reqOrderSave.setMchId(3); //此处为城市ID，必填
        } else {
            reqOrderSave.setMchId(2); //此处为城市ID，必填
        }
        //如果回调类型为0，则订单系统使用http方式进行回调；如果回调类型为1，使用mq进行处理
        if (callbackType.equals(Constants.IS_NO)) {
            reqOrderSave.setNotifyURL(payUrl);
            reqOrderSave.setCloseNotifyURL(closeOrderUrl);
            reqOrderSave.setRefundNotifyURL(refundUrl);
            reqOrderSave.setExceptionRefundNotify(exceptionRefundUrl);
            logger.info("订单号：{}，支付使用http回调处理。", orderNo);
        } else {
            logger.info("订单号：{}，支付使用mq消息处理。", orderNo);
        }

        reqOrderSave.setOrderDescribe("App会员卡开卡");
        reqOrderSave.setOrderURL(tbBizPlace.getBizPlaceUrl());
        reqOrderSave.setOutTradeNo(orderNo);
        reqOrderSave.setPayNote("");
        reqOrderSave.setUserClientIp("");
        reqOrderSave.setPayTimeOut(PlaceConstants.PAYTIMEOUT);
        reqOrderSave.setUid(userId);
        reqOrderSave.setShowURL(tbBizPlace.getBizPlaceUrl());
        reqOrderSave.setLarkAppId(larkAppId);
//        reqOrderSave.setEggInfo(tbBizPlace.getName() + "订场费");
//        reqOrderSave.setEggReceiver("百灵鸟");
        reqOrderSave.setVer(ver);//设置版本号

        reqOrderSave.setService(PlaceConstants.SERVICE_CODE);
        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
            ReqProductDetail reqProductDetail = new ReqProductDetail();
            reqProductDetail.setShowURL(tbBizPlace.getBizPlaceUrl());

            reqProductDetail.setProductDesc(tbBizPlaceMemberCardType.getName());
            reqProductDetail.setProductId(tbBizPlaceMemberCardType.getId() + "");
            reqProductDetail.setProductName(tbBizPlaceMember.getUserName() + "开卡:" + tbBizPlaceMemberCardType.getName());
            reqProductDetail.setProductURL(tbBizPlace.getBizPlaceUrl());
            reqProductDetail.setQuantity(1);
            reqProductDetailList.add(reqProductDetail);
        reqOrderSave.setProductDetailList(reqProductDetailList);
        List<Integer> values = new ArrayList<>();
        values.add(PlaceConstants.PAY_WAY_ALIPAY);
        values.add(PlaceConstants.PAY_WAY_WEICHAT);
        values.add(PlaceConstants.PAY_WAY_WEICHATH5);
        values.add(PlaceConstants.PAY_WAY_UNION_PAY);
        values.add(PlaceConstants.PAY_WAY_APPLE_PAY);
        List<ReqPayInfo> payInfos = new ArrayList<>();
            if (values.contains(payTypeId)) {
                ReqPayInfo reqPayInfo = new ReqPayInfo();
                reqPayInfo.setPayId(payTypeId);
                reqPayInfo.setAmount(tbBizPlaceMemberCardType.getInitAmount());
                reqPayInfo.setPayType(PlaceConstants.APP_PAY_MEMBERCARD);
                payInfos.add(reqPayInfo);
                reqOrderSave.setOrderAmount(tbBizPlaceMemberCardType.getInitAmount());
            }else{
                return APIResponse.returnFail("不支持的支付方式" + payTypeId);
            }
        reqOrderSave.setPayInfos(payInfos);
        logger.debug("========================支付数据:reqOrderSave:{}", JSON.toJSONString(reqOrderSave));
        APIResponse<RespPreOrder> respPreOrderAPIResponse = orderPayService.submitOrder(reqOrderSaveAPIRequest);
        try {
            if (respPreOrderAPIResponse == null || !respPreOrderAPIResponse.isRet()) {
                if (respPreOrderAPIResponse.getErrcode() == 21012){
                    throw new BizException("当前支付方式不可用，请使用其他支付方式或稍后再试。");
                }
                throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
            }
        } catch (Exception e) {
            if (respPreOrderAPIResponse != null && !respPreOrderAPIResponse.isRet()) {
                logger.warn("uid：{} ，error：{} ", userId, respPreOrderAPIResponse.getErrmsg());
            } else {
                logger.warn("uid：{} ，error：{} ", userId, e.getMessage());
            }
            if (respPreOrderAPIResponse.getErrcode() == 21012){
                throw new BizException("当前支付方式不可用，请使用其他支付方式或稍后再试。");
            }
            throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
        }
        /*try {
            saveOrderInfo(userId, tbBizPlaceMemberCardType, tbBizPlace, tbBizPlaceMember, orderNo,
                strPlatform, respPreOrderAPIResponse, PlaceConstants.PLACE_OPEN_CARD_TYPE, payInfos);
        } catch (Exception e) {
            throw new BizException("增加会员开卡订单信息失败");
        }*/
        // 增加会员卡信息
        /*try {
            addMemberCard(userId, tbBizPlaceMemberCardType, innerCardNo);
        } catch (Exception e) {
            throw new BizException("增加会员卡信息失败");
        }*/
        // 增加会员卡开卡历史记录
        try {
            addOpenCardHistory(userId, tbBizPlaceMemberCardType, payTypeId, tbBizPlaceMember, orderNo,
                    respPreOrderAPIResponse.getData().getOrderNo(),
                    platformType, PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO,refereesId);
        }catch(Exception e){
            throw new BizException("增加会员卡开卡历史记录失败");
        }
        return respPreOrderAPIResponse;

    }

    private void saveOrderInfo(Integer userId, TbBizPlaceMemberCardType tbBizPlaceMemberCardType,
                               TbBizPlace tbBizPlace, TbBizPlaceMember tbBizPlaceMember, String orderNo,
                               String strPlatform, APIResponse<RespPreOrder> respPreOrderAPIResponse,
                               Integer type, List<ReqPayInfo> payInfos) throws Exception{
        // 增加会员卡订单
        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
        tbBizPlaceOrder.setPlaceId(tbBizPlace.getId());
        tbBizPlaceOrder.setCreateUid(userId);
        tbBizPlaceOrder.setDebit(tbBizPlaceMemberCardType.getInitAmount());
        tbBizPlaceOrder.setCustomerName(tbBizPlaceMember.getUserName());
        tbBizPlaceOrder.setOrderNo(respPreOrderAPIResponse.getData().getOrderNo());
        tbBizPlaceOrder.setPlaceOrderId(orderNo);
        tbBizPlaceOrder.setDate(new Date());
        tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
        tbBizPlaceOrder.setUid(userId);
        tbBizPlaceOrder.setMobile(tbBizPlaceMember.getMobile());
        tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_MEMBERCARD);
        tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_OPEN_CARD);
        tbBizPlaceOrder.setPlatform(Integer.parseInt(strPlatform));
        tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder);

        // 增加会员卡详情订单
        TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
        tbBizPlaceOrderItem.setUnitSalePlanId(tbBizPlaceMemberCardType.getId());
        tbBizPlaceOrderItem.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
        tbBizPlaceOrderItem.setItemType(type);
        tbBizPlaceOrderItem.setSalePrice(tbBizPlaceMemberCardType.getInitAmount());
        tbBizPlaceOrderItem.setCreateUid(userId);
        tbBizPlaceOrderItem.setConsumeTime(new Date());
        tbBizPlaceOrderItemMapper.insertSelective(tbBizPlaceOrderItem);

        if(CollectionUtils.isNotEmpty(payInfos)){
            for (ReqPayInfo payInfo : payInfos) {
                TbBizPlacePayItem record = new TbBizPlacePayItem();
                record.setPlaceOrderId(orderNo);
                record.setAmount(payInfo.getAmount());
                record.setPayType(payInfo.getPayId());
                record.setAmountType(PlaceConstants.DEBIT_TYPE);
                if(PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfo.getPayId())){
                    record.setSubjectCode(payInfo.getSubjectCode());
                }
                tbBizPlacePayItemMapper.insertSelective(record);
            }
        }
    }

    private void addOpenCardHistory(Integer userId, TbBizPlaceMemberCardType tbBizPlaceMemberCardType,
                                    Integer payTypeId, TbBizPlaceMember tbBizPlaceMember, String orderNo, String no,
                                    Integer platform, byte state,Integer refereesId) throws Exception{
        TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
//        opHistory.setMemo(tbBizPlaceMemberCard.getMemo());// 备注
        opHistory.setRefereesId(refereesId);
        opHistory.setCreateUid(userId);
        opHistory.setPlaceId(tbBizPlaceMemberCardType.getPlaceId());
        opHistory.setAmount(tbBizPlaceMemberCardType.getInitAmount());
        opHistory.setUid(userId);
        opHistory.setCardTypeName(tbBizPlaceMemberCardType.getName());
        opHistory.setOpTypeName("APP-会员开卡");
        opHistory.setOpBeforeAmount(BigDecimal.ZERO);
        opHistory.setOpBeforeGiveAmount(BigDecimal.ZERO);
        opHistory.setOpAfterAmount(tbBizPlaceMemberCardType.getInitAmount());
        opHistory.setOpAfterGiveAmount(tbBizPlaceMemberCardType.getGiveAmount());
        opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
        opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_COMMONPAY);
        opHistory.setCardTypeId(tbBizPlaceMemberCardType.getId());
        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == tbBizPlaceMemberCardType.getType()) {
            // 次卡的情况
            opHistory.setOpBeforeNumbers(0);
            opHistory.setOpAfterNumbers(tbBizPlaceMemberCardType.getFrequency());
            opHistory.setOpCardCount(tbBizPlaceMemberCardType.getFrequency());
            opHistory.setOpBeforeAmount(BigDecimal.ZERO);
            opHistory.setOpAfterAmount(BigDecimal.ZERO);
        }
        if (!StringUtils.isEmpty(tbBizPlaceMember)) {
            opHistory.setUserName(tbBizPlaceMember.getUserName());
            opHistory.setMobile(tbBizPlaceMember.getMobile());
        }

        opHistory.setState(state);
        opHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
//        opHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberCardType.getPlaceId()));
        opHistory.setNo(no);
//        opHistory.setInnerCardNo(innerCardNo);
        opHistory.setOrderNo(orderNo);
        opHistory.setPayType(payTypeId);
        opHistory.setPlatform(platform);// APP
        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceMemberCardType.getPlaceId());
        opHistory.setBusinessMode(tbBizPlace.getBusinessMode());
        addPlaceMemberCardOpRecord(opHistory);
    }

    public TbBizPlaceMemberCard addMemberCard(Integer userId, TbBizPlaceMemberCardType tbBizPlaceMemberCardType,
                               String innerCardNo,Integer refereesId) throws Exception {
        TbBizPlaceMemberCard tbBizPlaceMemberCard = new TbBizPlaceMemberCard();
        tbBizPlaceMemberCard.setRefereesId(refereesId);
        tbBizPlaceMemberCard.setInnerCardNo(innerCardNo);
        tbBizPlaceMemberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        tbBizPlaceMemberCard.setSourceType(PlaceConstants.PLACE_MEMBER);
        tbBizPlaceMemberCard.setCardType(tbBizPlaceMemberCardType.getType());
        tbBizPlaceMemberCard.setCardTypeId(tbBizPlaceMemberCardType.getId());
        tbBizPlaceMemberCard.setCardName(tbBizPlaceMemberCardType.getName());
        tbBizPlaceMemberCard.setMemberUid(userId);
        tbBizPlaceMemberCard.setPlaceId(tbBizPlaceMemberCardType.getPlaceId());
        tbBizPlaceMemberCard.setDiscount(tbBizPlaceMemberCardType.getDiscount());
        if (tbBizPlaceMemberCardType.getType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER) {
            tbBizPlaceMemberCard.setAmount(tbBizPlaceMemberCardType.getInitAmount());
            tbBizPlaceMemberCard.setNumbers(tbBizPlaceMemberCardType.getFrequency());
            tbBizPlaceMemberCard.setSurplusNumbers(tbBizPlaceMemberCardType.getFrequency());
        } else {
            tbBizPlaceMemberCard.setAmount(tbBizPlaceMemberCardType.getInitAmount());
            tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCardType.getInitAmount());
            tbBizPlaceMemberCard.setGiveAmount(tbBizPlaceMemberCardType.getGiveAmount());
        }
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getAvailableTerm())){
            Date expiryDate = DateUtils.addMonth(new Date(),
                    tbBizPlaceMemberCardType.getAvailableTerm());
            tbBizPlaceMemberCard.setDeadLineTime(expiryDate);
        }

        //本金余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getInitAmount())){
            tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCardType.getInitAmount());
        }
        // 赠送余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getGiveAmount())){
            tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCardType.getGiveAmount());
        }
        // 剩余次数
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getFrequency())){
            tbBizPlaceMemberCard.setSurplusNumbers(tbBizPlaceMemberCardType.getFrequency());
        }
        tbBizPlaceMemberCard.setCategoryIds(tbBizPlaceMemberCardType.getCategoryIds());
        tbBizPlaceMemberCard.setAvailableStartTime(tbBizPlaceMemberCardType.getAvailableStartTime());
        tbBizPlaceMemberCard.setAvailableEndTime(tbBizPlaceMemberCardType.getAvailableEndTime());
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getAvailableTerm())) {
            tbBizPlaceMemberCard.setDeadLineTime(DateUtils.addMonth(new Date(),
                    tbBizPlaceMemberCardType.getAvailableTerm()));
        }
        int flag = this.tbBizPlaceMemberCardMapper.insertSelective(tbBizPlaceMemberCard);
        if (flag != 0){
            return tbBizPlaceMemberCard;
        }
        return null;
    }

    public APIResponse<?> vaildCardByID(Integer cardID,Integer placeId) {
        if (StringUtils.isEmpty(cardID)) {
            return APIResponse.returnFail("会员卡充值失败");
        }
        TbBizPlaceMemberCard tbBizPlaceMemberCard = this.tbBizPlaceMemberCardMapper.selectByPrimaryKey(cardID);
        if (StringUtils.isEmpty(tbBizPlaceMemberCard) || StringUtils.isEmpty(tbBizPlaceMemberCard.getCardTypeId())) {
            return APIResponse.returnFail("该会员卡不存在");
        }
        if(tbBizPlaceMemberCard.getPlaceId()!=null&&placeId!=null){
            if(!tbBizPlaceMemberCard.getPlaceId().equals(placeId)){
                return APIResponse.returnFail("共享会员不能跨场馆充值");
            }
        }
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = this.tbBizPlaceMemberCardTypeMapper
                .selectByPrimaryKey(tbBizPlaceMemberCard.getCardTypeId());
        if (StringUtils.isEmpty(tbBizPlaceMemberCardType)) {
            return APIResponse.returnFail("该会员卡类型不存在");
        }
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getStatus())
                && tbBizPlaceMemberCardType.getStatus() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_NO) {
            return APIResponse.returnFail("该会员卡类型已停用，不能充值");
        }
        if(tbBizPlaceMemberCard.getIsOldMember()==Constants.YES){
            return APIResponse.returnFail("该老会员卡不能充值");
        }
        if (tbBizPlaceMemberCardType.getIsDelete().intValue() == Constants.IS_DELETE_TRUE) {
            return APIResponse.returnFail("该会员卡已被删除");
        }
        TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
        example.createCriteria().andUidEqualTo(tbBizPlaceMemberCard.getMemberUid());
        List<TbBizPlaceMember> tbBizPlaceMembers = tbBizPlaceMemberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(tbBizPlaceMembers) && StringUtils.isEmpty(tbBizPlaceMembers.get(0))) {
            return APIResponse.returnFail("该会员ID不存在:" + tbBizPlaceMemberCard.getMemberUid());
        }
        if(tbBizPlaceMemberCard.getCardType()==4){
            if (!tbBizPlaceMemberCardType.getGiveAmount().equals(new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_UP))) {
                return APIResponse.returnFail("次卡没有赠送金额");
            }
            if (!tbBizPlaceMemberCardType.getDiscount().equals(100d)) {
                return APIResponse.returnFail("次卡没有折扣");
            }
            if (!tbBizPlaceMemberCardType.getGiveAmountIsUse().equals(0)) {
                return APIResponse.returnFail("次卡赠送金额不可用");
            }
            if (!tbBizPlaceMemberCardType.getInitAmount().equals(tbBizPlaceMemberCard.getAmount())) {
                return APIResponse.returnFail("次卡充值金额与上次的不一致");
            }
            if (!tbBizPlaceMemberCardType.getFrequency().equals(tbBizPlaceMemberCard.getNumbers())) {
                return APIResponse.returnFail("次卡充值次数与上次的不一致");
            }
        }
        Map map = new HashMap();
        map.put("tbBizPlaceMember", tbBizPlaceMembers.get(0));
        map.put("tbBizPlaceMemberCard", tbBizPlaceMemberCard);
        map.put("tbBizPlaceMemberCardType", tbBizPlaceMemberCardType);

        return APIResponse.returnSuccess(map);

    }

    @Override
    public PageObj<List<TbBizPlaceMemberOpHistory>> getMemberOpHistory(Integer userId,
                                                                       TbBizPlaceMemberCard tbBizPlaceMemberCard,
                                                                       Integer pageNum, Integer pageSize) {
        TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
       TbBizPlaceMemberOpHistoryExample.Criteria criteria = tbBizPlaceMemberOpHistoryExample.createCriteria();
        criteria.andUidEqualTo(userId).andStateEqualTo(Constants.BYTE_ONE);
        if (!StringUtils.isEmpty(tbBizPlaceMemberCard) && !StringUtils.isEmpty(tbBizPlaceMemberCard.getInnerCardNo())){
            criteria.andInnerCardNoEqualTo(tbBizPlaceMemberCard.getInnerCardNo());
            criteria.andSrcNotEqualTo(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME);
        }
        tbBizPlaceMemberOpHistoryExample.setOrderByClause("create_time desc");
        int count = this.tbBizPlaceMemberOpHistoryMapper.countByExample(tbBizPlaceMemberOpHistoryExample);
        if (count > 0){
            tbBizPlaceMemberOpHistoryExample.setPage(Page.createPage(count, pageNum, pageSize));
            List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistory = tbBizPlaceMemberOpHistoryMapper
                    .selectByExample(tbBizPlaceMemberOpHistoryExample);
            PageObj<List<TbBizPlaceMemberOpHistory>> pageObj = new PageObj<>();
            pageObj.setTotal(count);
            pageObj.setPageNum(pageNum);
            pageObj.setSize(pageSize);
            pageObj.setItems(tbBizPlaceMemberOpHistory);
            return pageObj;
        }
        return null;
    }

    @Override
    public TbBizPlaceMemberCard getTbBizPlaceMemberCardByTypeId(Integer userId, Integer cardTypeId) {
        TbBizPlaceMemberCardExample example = new TbBizPlaceMemberCardExample();
        example.createCriteria().andMemberUidEqualTo(userId).andCardTypeIdEqualTo(cardTypeId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE)
                .andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCards = tbBizPlaceMemberCardMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(tbBizPlaceMemberCards)){
            return tbBizPlaceMemberCards.get(0);
        }
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> vipCardReChargeDetail(Integer userId, Integer cardTypeId, Integer payTypeId,
                                                TbBizPlaceMemberCard tbBizPlaceMemberCard, Integer platformType,Integer refereesId) {
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(cardTypeId);
        if (StringUtils.isEmpty(tbBizPlaceMemberCardType)){
            return APIResponse.returnFail("没有会员卡类型");
        }

        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceMemberCardType.getPlaceId());
        if (StringUtils.isEmpty(tbBizPlace)) {
            return APIResponse.returnFail("没有相关场馆信息");
        }

        TbBizPlaceMember tbBizPlaceMember = null;

        TbBizPlaceMemberExample tbBizPlaceMemberExample = new TbBizPlaceMemberExample();
        tbBizPlaceMemberExample.createCriteria().andUidEqualTo(userId);
        List<TbBizPlaceMember> tbBizPlaceMembers = this.tbBizPlaceMemberMapper.selectByExample(tbBizPlaceMemberExample);
        if (CollectionUtils.isEmpty(tbBizPlaceMembers)){
            return APIResponse.returnFail("用户不是会员");
        }else{
            tbBizPlaceMember = tbBizPlaceMembers.get(0);
        }


        // 支付会员卡
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        String ver = httpServletRequest.getHeader("APPVersion");

        // 获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, userId);

        //// TODO: 16/11/14 测试用
//        strPlatform = "2";
//        ver = "2.1.1-DEBUG";

        // todo 调用支付
        //设置回调方式
        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_ORDER_CALLBACK_TYPE.getCode());
        Integer callbackType = 0;
        if (parameter != null && parameter.getParameterValue() != null) {
            callbackType = Integer.valueOf(parameter.getParameterValue());
        }
        //调用订单系统，获取预支付信息
        com.quanyan.api.APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new com.quanyan.api.APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();
        reqOrderSaveAPIRequest.setData(reqOrderSave);
        reqOrderSave.setSourceBusinessId(Constants.PLACE_TICKET_CODE);
        reqOrderSave.setSourceSystemId(Constants.PLACE_SYSTEM_CODE);
        reqOrderSave.setPlatformType(platformType);//设置平台类型
        reqOrderSave.setContactMobile(tbBizPlaceMember.getMobile());
        reqOrderSave.setContactName(tbBizPlaceMember.getUserName());
        reqOrderSave.setExtraParam("");
        if (tbBizPlace.getCityId() != null && tbBizPlace.getCityId().equals(3)) {
            reqOrderSave.setMchId(3); //此处为城市ID，必填
        } else {
            reqOrderSave.setMchId(2); //此处为城市ID，必填
        }
        //如果回调类型为0，则订单系统使用http方式进行回调；如果回调类型为1，使用mq进行处理
        if (callbackType.equals(Constants.IS_NO)) {
            reqOrderSave.setNotifyURL(payUrl);
            reqOrderSave.setCloseNotifyURL(closeOrderUrl);
            reqOrderSave.setRefundNotifyURL(refundUrl);
            reqOrderSave.setExceptionRefundNotify(exceptionRefundUrl);
            logger.info("订单号：{}，支付使用http回调处理。", orderNo);
        } else {
            logger.info("订单号：{}，支付使用mq消息处理。", orderNo);
        }

        reqOrderSave.setOrderDescribe("App会员卡充值");
        reqOrderSave.setOrderURL(tbBizPlace.getBizPlaceUrl());
        reqOrderSave.setOutTradeNo(orderNo);
        reqOrderSave.setPayNote("");
        reqOrderSave.setUserClientIp("");
        reqOrderSave.setPayTimeOut(PlaceConstants.PAYTIMEOUT);
        reqOrderSave.setUid(userId);
        reqOrderSave.setShowURL(tbBizPlace.getBizPlaceUrl());
//        reqOrderSave.setEggInfo(tbBizPlace.getName() + "订场费");
//        reqOrderSave.setEggReceiver("百灵鸟");
        reqOrderSave.setVer(ver);//设置版本号

        reqOrderSave.setService(PlaceConstants.SERVICE_CODE);
        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        ReqProductDetail reqProductDetail = new ReqProductDetail();
        reqProductDetail.setShowURL(tbBizPlace.getBizPlaceUrl());

        reqProductDetail.setProductDesc(tbBizPlaceMemberCardType.getName());
        reqProductDetail.setProductId(tbBizPlaceMemberCardType.getId() + "");
        reqProductDetail.setProductName(tbBizPlaceMember.getUserName() + "充值:" + tbBizPlaceMemberCardType.getName());
        reqProductDetail.setProductURL(tbBizPlace.getBizPlaceUrl());
        reqProductDetail.setQuantity(1);
        reqProductDetailList.add(reqProductDetail);
        reqOrderSave.setProductDetailList(reqProductDetailList);
        List<Integer> values = new ArrayList<>();
        values.add(PlaceConstants.PAY_WAY_ALIPAY);
        values.add(PlaceConstants.PAY_WAY_WEICHAT);
        values.add(PlaceConstants.PAY_WAY_WEICHATH5);
        values.add(PlaceConstants.PAY_WAY_UNION_PAY);
        values.add(PlaceConstants.PAY_WAY_APPLE_PAY);
        List<ReqPayInfo> payInfos = new ArrayList<>();
        if (values.contains(payTypeId)) {
            ReqPayInfo reqPayInfo = new ReqPayInfo();
            reqPayInfo.setPayId(payTypeId);
            reqPayInfo.setAmount(tbBizPlaceMemberCardType.getInitAmount());
            reqPayInfo.setPayType(PlaceConstants.APP_PAY_MEMBERCARD);
            payInfos.add(reqPayInfo);
            reqOrderSave.setOrderAmount(tbBizPlaceMemberCardType.getInitAmount());
        }else{
            return APIResponse.returnFail("不支持的支付方式" + payTypeId);
        }
        reqOrderSave.setPayInfos(payInfos);
        logger.debug("========================支付数据:reqOrderSave:{}", JSON.toJSONString(reqOrderSave));
        APIResponse<RespPreOrder> respPreOrderAPIResponse = orderPayService.submitOrder(reqOrderSaveAPIRequest);
        try {
            if (respPreOrderAPIResponse == null || !respPreOrderAPIResponse.isRet()) {
                if (respPreOrderAPIResponse.getErrcode() == 21012){
                    throw new BizException("当前支付方式不可用，请使用其他支付方式或稍后再试。");
                }
                throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
            }
        } catch (Exception e) {
            if (respPreOrderAPIResponse != null && !respPreOrderAPIResponse.isRet()) {
                logger.warn("uid：{} ，error：{} ", userId, respPreOrderAPIResponse.getErrmsg());
            } else {
                logger.warn("uid：{} ，error：{} ", userId, e.getMessage());
            }
            if (respPreOrderAPIResponse.getErrcode() == 21012){
                throw new BizException("当前支付方式不可用，请使用其他支付方式或稍后再试。");
            }
            throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
        }

        /*try {
            saveOrderInfo(userId, tbBizPlaceMemberCardType, tbBizPlace, tbBizPlaceMember, orderNo,
                    strPlatform, respPreOrderAPIResponse, PlaceConstants.PLACE_RECHARGE_CARD_TYPE, payInfos);
        } catch (Exception e) {
            throw new BizException("增加会员卡充值订单信息失败");
        }*/

        // 更新会员卡表数据
//        TbBizPlaceMemberCard memberCard = updateTbBizPlaceMemberCard(tbBizPlaceMemberCard, tbBizPlaceMemberCardType);

        // 增加会员卡充值历史记录
        try{
            addRechargeCardHistory(userId, tbBizPlaceMemberCard, tbBizPlaceMemberCardType, payTypeId,
                    tbBizPlaceMember, orderNo, respPreOrderAPIResponse.getData().getOrderNo(), platformType,
                    PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO,refereesId);
        }catch(Exception e){
            throw new BizException("增加会员卡充值历史记录失败");
        }
        return respPreOrderAPIResponse;
    }

    private void addRechargeCardHistory(Integer userId,TbBizPlaceMemberCard tbBizPlaceMemberCard,
                                        TbBizPlaceMemberCardType tbBizPlaceMemberCardType,
                                        Integer payTypeId, TbBizPlaceMember tbBizPlaceMember,
                                        String orderNo, String no, Integer platform, byte state,Integer refereesId) {
        TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
//        opHistory.setMemo(tbBizPlaceMemberCard.getMemo());// 备注
        opHistory.setRefereesId(refereesId);
        opHistory.setCreateUid(userId);
        opHistory.setPlaceId(tbBizPlaceMemberCardType.getPlaceId());
        opHistory.setAmount(tbBizPlaceMemberCardType.getInitAmount());
        opHistory.setUid(userId);
        opHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
        opHistory.setCardTypeName(tbBizPlaceMemberCardType.getName());
        opHistory.setOpTypeName("APP-会员充值");
        opHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount());
        opHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
        opHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount().add(opHistory.getAmount()));
        opHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceMemberCardType.getGiveAmount()));
        opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
        opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_COMMONPAY);
        opHistory.setCardTypeId(tbBizPlaceMemberCardType.getId());
        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == tbBizPlaceMemberCardType.getType()) {
            // 次卡的情况
            opHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
            opHistory.setOpAfterNumbers(tbBizPlaceMemberCardType.getFrequency() + tbBizPlaceMemberCard.getSurplusNumbers());
            opHistory.setOpCardCount(tbBizPlaceMemberCardType.getFrequency());
            opHistory.setOpBeforeAmount(BigDecimal.ZERO);
            opHistory.setOpAfterAmount(BigDecimal.ZERO);
        }
        if (!StringUtils.isEmpty(tbBizPlaceMember)) {
            opHistory.setUserName(tbBizPlaceMember.getUserName());
            opHistory.setMobile(tbBizPlaceMember.getMobile());
        }

        opHistory.setState(state);
        opHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE); // 收入
//        opHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberCardType.getPlaceId()));
        opHistory.setNo(no);
        opHistory.setOrderNo(orderNo);
        opHistory.setPayType(payTypeId);
        opHistory.setPlatform(platform);// APP
        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceMemberCardType.getPlaceId());
        opHistory.setBusinessMode(tbBizPlace.getBusinessMode());
        addPlaceMemberCardOpRecord(opHistory);
    }

    @NotNull
    private TbBizPlaceMemberCard updateTbBizPlaceMemberCard(TbBizPlaceMemberCard tbBizPlaceMemberCard, TbBizPlaceMemberCardType tbBizPlaceMemberCardType) {
        TbBizPlaceMemberCard memberCard = new TbBizPlaceMemberCard();
        memberCard.setId(tbBizPlaceMemberCard.getId());
        //充值后有效期
        Date expiryDate = DateUtils.addMonth(tbBizPlaceMemberCard.getDeadLineTime(),
                tbBizPlaceMemberCardType.getAvailableTerm());
        memberCard.setDeadLineTime(expiryDate);
        //本金余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getInitAmount())){
            tbBizPlaceMemberCard.setSurplusAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusAmount())
                    ? BigDecimal.ZERO : tbBizPlaceMemberCard.getSurplusAmount());
            BigDecimal surplusAmount = tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCardType.getInitAmount());
            memberCard.setSurplusAmount(surplusAmount);
        }
        // 赠送余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getGiveAmount())){
            tbBizPlaceMemberCard.setSurplusGiveAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusGiveAmount())
                    ? BigDecimal.ZERO : tbBizPlaceMemberCard.getSurplusGiveAmount());
            BigDecimal surplusGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount()
                    .add(tbBizPlaceMemberCardType.getGiveAmount());
            memberCard.setSurplusGiveAmount(surplusGiveAmount);
        }
        // 剩余次数
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getFrequency())){
            Integer cardNumbers = 0;
            if (tbBizPlaceMemberCard.getSurplusNumbers() != null){
                cardNumbers = tbBizPlaceMemberCard.getSurplusNumbers();
            }
            Integer surplusNumbers = cardNumbers + tbBizPlaceMemberCardType.getFrequency();
            memberCard.setSurplusNumbers(surplusNumbers);
        }
        // 更新会员卡表数据
        this.updatePlaceMemberCard(memberCard);
        return memberCard;
    }

    @Override
    public List<RespCardPayList> getRespCardPayList(List<TbBizPlaceMemberOpHistory> list) {
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        RespCardPayList respCardPayList = null;
        List<RespCardPayList> respCardPayLists = new ArrayList<>();
        for (TbBizPlaceMemberOpHistory tbpmo : list){
            respCardPayList = new RespCardPayList();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            respCardPayList.setPayTime(sdf.format(tbpmo.getCreateTime()));
            respCardPayList.setFeeName(tbpmo.getOpTypeName());
            respCardPayList.setState(tbpmo.getType().intValue());
            if (!StringUtils.isEmpty(tbpmo.getInnerCardNo())){
                TbBizPlaceMemberCard tbBizPlaceMemberCard = this.getPlaceMemberCardInfo(tbpmo.getInnerCardNo(),
                        null, null);
                if (!StringUtils.isEmpty(tbBizPlaceMemberCard)){
                    respCardPayList.setCardType(tbBizPlaceMemberCard.getCardType().intValue());

                }
                if (respCardPayList.getState() == PlaceConstants.DEBIT_TYPE.intValue()){
                    if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.intValue()){
                        respCardPayList.setFee( "" +
                                (tbpmo.getOpAfterNumbers().intValue() - tbpmo.getOpBeforeNumbers().intValue()));
                    }else {
                        if (!StringUtils.isEmpty(tbpmo.getOpAfterAmount()))
                        respCardPayList.setFee("" + tbpmo.getOpAfterAmount().subtract(tbpmo.getOpBeforeAmount()));
                    }
                }else {
                    if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.intValue()){
                        respCardPayList.setFeeType( "" +
                                (tbpmo.getOpAfterNumbers().intValue() - tbpmo.getOpBeforeNumbers().intValue()));
                    }else {
                        if (!StringUtils.isEmpty(tbpmo.getOpAfterAmount()))
                            respCardPayList.setFeeType("" + tbpmo.getOpAfterAmount().subtract(tbpmo.getOpBeforeAmount()));
                    }
                }

            }
            respCardPayLists.add(respCardPayList);
        }
        return respCardPayLists;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    public APIResponse<?> orderCancelOperate(ReqOrderOperate reqOrderOperate) {
        //设置订单状态为关闭状态
        /*TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
        TbBizPlaceOrder record = new TbBizPlaceOrder();
        record.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
        record.setOrderStatusChangeDate(new Date());
        record.setEndTime(new Date());
        //// TODO: 16/11/15 测试用
        record.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);*/

        //更改订单支付明细的状态为取消状态
        /*TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
        tbBizPlacePayItem.setAmountType(PlaceConstants.CANCEL_TYPE);
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
        tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,tbBizPlacePayItemExample);*/

        return APIResponse.returnSuccess();
//        return APIResponse.returnSuccess("会员卡订单取消成功！");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    public APIResponse<?> orderCompletePayOperate(ReqOrderOperate reqOrderOperate, TbBizPlaceOrder tbBizPlaceOrder) {
        //设置订单状态为已经付款状态
        /*TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
        tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

        TbBizPlaceOrder record = new TbBizPlaceOrder();
        record.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
        record.setPayStatus(PlaceConstants.PAY_STATUS);
        Date date = new Date();
        record.setOrderStatusChangeDate(date);
        record.setPaymentTime(date);
        record.setEndTime(date);
        //// TODO: 16/11/15 测试用
        record.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample1);

        List<Integer> values = new ArrayList<>();
        values.add(PlaceConstants.PAY_WAY_ALIPAY);
        values.add(PlaceConstants.PAY_WAY_WEICHAT);
        values.add(PlaceConstants.PAY_WAY_WEICHATH5);
        values.add(PlaceConstants.PAY_WAY_UNION_PAY);
        values.add(PlaceConstants.PAY_WAY_APPLE_PAY);

        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
        tbBizPlacePayItemCriteria.andPayTypeIn(values);
        List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
        if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
            return APIResponse.returnFail("没有该条订单信息！");
        }
        TbBizPlaceOrderItemExample example = new TbBizPlaceOrderItemExample();
        example.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrder.getPlaceOrderId());
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = tbBizPlaceOrderItemMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
            return APIResponse.returnFail("没有该条订单详细信息！");
        }*/
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper
                .selectByPrimaryKey(1);
        Map cardMap = new HashMap();
        cardMap.put("placeId", tbBizPlaceMemberCardType.getPlaceId());
        String innerCardNo = cardNoService.getCardNo(cardMap);
        TbBizPlaceMember tbBizPlaceMember = this.getPlaceMemberByUid(tbBizPlaceOrder.getUid());

        if (tbBizPlaceOrder.getUseType() == PlaceConstants.ORDER_USE_OPEN_CARD){
            try{
                this.addMemberCard(tbBizPlaceOrder.getUid(), tbBizPlaceMemberCardType, innerCardNo,null);
            }catch (Exception e){
                throw new BizException("增加会员开卡失败");
            }
//            try{
//                this.addOpenCardHistory(tbBizPlaceOrder.getUid(), innerCardNo, tbBizPlaceMemberCardType,
//                        tbBizPlacePayItemList.get(0).getPayType(), tbBizPlaceMember, tbBizPlaceOrder);
//            }catch (Exception e){
//                throw new BizException("增加会员开卡交易信息失败");
//            }
        }

        if (tbBizPlaceOrder.getUseType() == PlaceConstants.ORDER_USE_RECHARGE_CARD){
            TbBizPlaceMemberCard tbBizPlaceMemberCard = getTbBizPlaceMemberCardByTypeId(tbBizPlaceOrder.getUid(),
                    tbBizPlaceMemberCardType.getId());
            try{
                this.updateTbBizPlaceMemberCard(tbBizPlaceMemberCard, tbBizPlaceMemberCardType);
            }catch (Exception e){
                throw new BizException("增加会员卡充值失败");
            }
            /*try{
                this.addRechargeCardHistory(tbBizPlaceOrder.getUid(), tbBizPlaceMemberCard, tbBizPlaceMemberCardType,
                        tbBizPlacePayItemList.get(0).getPayType(), tbBizPlaceMember, tbBizPlaceOrder);
            }catch (Exception e){
                throw new BizException("增加会员卡充值交易信息失败");
            }*/
        }

        return APIResponse.returnSuccess("会员卡订单支付成功！");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    public APIResponse orderUnsubscribeOperate(ReqOrderOperate reqOrderOperate, TbBizPlaceOrder tbBizPlaceOrder) {
        /*TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
        tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

        TbBizPlaceOrder tbBizPlaceRecord = new TbBizPlaceOrder();
        tbBizPlaceRecord.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
        tbBizPlaceRecord.setOrderStatusChangeDate(new Date());
        //// TODO: 16/11/15 测试用
        tbBizPlaceRecord.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);

        tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceRecord, tbBizPlaceOrderExample1);
        return APIResponse.returnSuccess("会员卡订单退款成功！");*/
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse<?> orderCompleteUnsubscribeOperate(ReqOrderOperate reqOrderOperate, TbBizPlaceOrder tbBizPlaceOrder) {
        /*TbBizPlaceOrder record = new TbBizPlaceOrder();
        //设置支付状态
        if (reqOrderOperate.getExceptionFlag()){
            record.setPayStatus(PlaceConstants.REFUNDING_EXCEPTION_STATUS);
        }
        else {
            record.setPayStatus(PlaceConstants.REFUNDING_STATUS);
        }

        //设置订单状态和支付状态为已经退款状态
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

        record.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
        Date date = new Date();
        record.setOrderStatusChangeDate(date);
        record.setRefundTime(date);
        record.setEndTime(date);
        record.setCredit(tbBizPlaceOrder.getDebit());
        //// TODO: 16/11/15 测试用
        record.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

        //更改订单支付明细的状态为退款状态
        TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
        tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
        tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem, tbBizPlacePayItemExample);
        return APIResponse.returnSuccess("订单退款成功！");*/
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse<?> orderCancleToUnsubscribeOperate(ReqOrderOperate reqOrderOperate, TbBizPlaceOrder tbBizPlaceOrder) {
        /*TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
        tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

        TbBizPlaceOrder tbBizPlaceRecord = new TbBizPlaceOrder();
        tbBizPlaceRecord.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
        tbBizPlaceRecord.setOrderStatusChangeDate(new Date());
        //// TODO: 16/11/15 测试用
        tbBizPlaceRecord.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceRecord, tbBizPlaceOrderExample1);

        List<Integer> values = new ArrayList<>();
        values.add(PlaceConstants.PAY_WAY_ALIPAY);
        values.add(PlaceConstants.PAY_WAY_WEICHAT);
        values.add(PlaceConstants.PAY_WAY_WEICHATH5);
        values.add(PlaceConstants.PAY_WAY_UNION_PAY);
        values.add(PlaceConstants.PAY_WAY_APPLE_PAY);
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
        tbBizPlacePayItemCriteria.andPayTypeIn(values);
        List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
        if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
            APIResponse.returnFail("没有该条订单信息！");
        }

        return APIResponse.returnSuccess("订单退款受理成功！");*/
        return APIResponse.returnSuccess();

    }

    @Override
    public TbBizPlaceMemberOpHistory getTbBizPlaceMemberOpHistoryByOrderNo(String orderNo, Byte state) {
        TbBizPlaceMemberOpHistoryExample example =  new TbBizPlaceMemberOpHistoryExample();
        example.createCriteria().andOrderNoEqualTo(orderNo)
                .andStateEqualTo(state);

        List<TbBizPlaceMemberOpHistory> list = tbBizPlaceMemberOpHistoryMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    @Override
    public TbBizPlaceMemberCard getTbBizPlaceMemberCardByInnerCardNo(String innerCardNo) {
        TbBizPlaceMemberCardExample example = new TbBizPlaceMemberCardExample();
        example.createCriteria().andInnerCardNoEqualTo(innerCardNo);
        example.setOrderByClause("id desc for update");
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCards = tbBizPlaceMemberCardMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(tbBizPlaceMemberCards)){
            return null;
        }
        return tbBizPlaceMemberCards.get(0);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> updateMemberCardByHistory(String placeOrderId) {
        if (StringUtils.isEmpty(placeOrderId) || !placeOrderId.startsWith(Constants.PLACE_SYSTEM)){
            return APIResponse.returnFail("订单号错误");
        }
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = this
                .getTbBizPlaceMemberOpHistoryByOrderNo(placeOrderId,  PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
        if (StringUtils.isEmpty(tbBizPlaceMemberOpHistory)){
            return APIResponse.returnFail(placeOrderId + "--没有充值记录");
        }
        TbBizPlaceMemberCard tbBizPlaceMemberCard = this
                .getTbBizPlaceMemberCardByInnerCardNo(tbBizPlaceMemberOpHistory.getInnerCardNo());
        if (StringUtils.isEmpty(tbBizPlaceMemberCard)){
            return APIResponse.returnFail(tbBizPlaceMemberOpHistory.getInnerCardNo() + "没有此会员卡");
        }

        //充值后有效期
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = this
                .getMemberTypeById(tbBizPlaceMemberCard.getCardTypeId());
        Date expiryDate = DateUtils.addMonth(tbBizPlaceMemberCard.getDeadLineTime(),
                tbBizPlaceMemberCardType.getAvailableTerm());
        tbBizPlaceMemberCard.setDeadLineTime(expiryDate);

        //本金余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getAmount())){
            tbBizPlaceMemberCard.setSurplusAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusAmount())
                    ? BigDecimal.ZERO : tbBizPlaceMemberCard.getSurplusAmount());
            BigDecimal amount = tbBizPlaceMemberOpHistory.getAmount();
            BigDecimal surplusAmount = tbBizPlaceMemberCard.getSurplusAmount().add(amount);
            tbBizPlaceMemberCard.setSurplusAmount(surplusAmount);
        }
        // 赠送余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpBeforeGiveAmount())
                && !StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpAfterGiveAmount())){
            tbBizPlaceMemberCard.setSurplusGiveAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusGiveAmount())
                    ? BigDecimal.ZERO
                    : tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceMemberOpHistory.getOpAfterGiveAmount()
                    .subtract(tbBizPlaceMemberOpHistory.getOpBeforeGiveAmount())));
            /*BigDecimal giveAmount = tbBizPlaceMemberOpHistory.getOpAfterGiveAmount()
                    .subtract(tbBizPlaceMemberOpHistory.getOpBeforeAmount());

            BigDecimal surplusGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount()
                    .add(giveAmount);
            tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);*/
        }
        // 剩余次数
        if (!StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpBeforeNumbers())
                && !StringUtils.isEmpty(tbBizPlaceMemberOpHistory.getOpAfterAmount())){
            Integer frequency = tbBizPlaceMemberOpHistory.getOpAfterNumbers()
                    - tbBizPlaceMemberOpHistory.getOpBeforeNumbers();
            Integer cardNumbers = 0;
            if (tbBizPlaceMemberCard.getSurplusNumbers() != null){
                cardNumbers = tbBizPlaceMemberCard.getSurplusNumbers();
            }
            Integer surplusNumbers = cardNumbers + frequency;
            tbBizPlaceMemberCard.setSurplusNumbers(surplusNumbers);
        }
        try{
            this.updatePlaceMemberCard(tbBizPlaceMemberCard);
        }catch (Exception e){
            throw new BizException("更新会员卡信息失败");
        }
        return APIResponse.returnSuccess();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> addMemberCardByHistory(String placeOrderId,Integer refereesId) {
        if (StringUtils.isEmpty(placeOrderId) || !placeOrderId.startsWith(Constants.PLACE_SYSTEM)){
            return APIResponse.returnFail("订单号错误");
        }
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = this
                .getTbBizPlaceMemberOpHistoryByOrderNo(placeOrderId,  PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
        if (StringUtils.isEmpty(tbBizPlaceMemberOpHistory)){
            return APIResponse.returnFail(placeOrderId + "--没有开卡记录");
        }

        TbBizPlaceMember tbBizPlaceMember = this.getPlaceMemberByUid(tbBizPlaceMemberOpHistory.getUid());
        if (StringUtils.isEmpty(tbBizPlaceMember)){
            return APIResponse.returnFail("没有此会员");
        }
        tbBizPlaceMember.setStatus(PlaceConstants.PLACE_MEMBER_STATUS_NORMAL);
        tbBizPlaceMemberMapper.updateByPrimaryKeySelective(tbBizPlaceMember);

        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = this
                .getMemberTypeById(tbBizPlaceMemberOpHistory.getCardTypeId());
        if (null == tbBizPlaceMemberCardType){
            return APIResponse.returnFail("没有此类型的会员卡");
        }
        Map cardMap = new HashMap();
        cardMap.put("placeId", tbBizPlaceMemberOpHistory.getPlaceId());
        String innerCardNo = cardNoService.getCardNo(cardMap);
        logger.info("开通会员卡号:" + innerCardNo);
        TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
        try{
            tbBizPlaceMemberCard = this.addMemberCard(tbBizPlaceMemberOpHistory.getUid(),
                    tbBizPlaceMemberCardType, innerCardNo,refereesId);
        }catch (Exception e){
            throw new BizException("增加会员卡信息失败" + e.getMessage());
        }

        try {
            if (!StringUtils.isEmpty(tbBizPlaceMemberCard)) {
                //更新操作历史记录
                tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
                this.tbBizPlaceMemberOpHistoryMapper.updateByPrimaryKey(tbBizPlaceMemberOpHistory);
            }
        }catch (Exception e){
            throw new BizException("更新会员操作历史记录信息失败" + e.getMessage());
        }
        return APIResponse.returnSuccess(tbBizPlaceMemberCard);
    }

    @Override
    public List<RespMemberCardType> queryMemberTypeListExport(PlaceMemberTypeVo placeMemberTypeVo) {
        if (!StringUtils.isEmpty(placeMemberTypeVo.getPlace())){
            placeMemberTypeVo.setPlace(placeMemberTypeVo.getPlace().trim());
        }
        List<RespMemberCardType> list = vPlaceMemberMapper.getRespMemberCardTypesByTerm(placeMemberTypeVo);
        list = this.tb2RespMemberCardType(list);
        return list;
    }

    /**
     * 查询指定uid是否在当前场馆会员表中存在
     * @param uid
     * @return
     */
    public boolean isExistsPlaceMember(Integer uid){
        TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
        TbBizPlaceMemberExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        List<TbBizPlaceMember> placeMembers = tbBizPlaceMemberMapper.selectByExample(example);
        if (null != placeMembers && placeMembers.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public TbBizPlaceMemberOpHistory addLogOffMemberCardByHistory(TbBizPlaceMemberCard tbBizPlaceMemberCard,
                                                                  Integer userId, Integer createUid, Integer platform) {
        if (null != tbBizPlaceMemberCard && null != tbBizPlaceMemberCard.getId()){
            TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper
                    .selectByPrimaryKey(tbBizPlaceMemberCard.getCardTypeId());
            TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
            opHistory.setMemo(tbBizPlaceMemberCard.getMemo());// 备注
            opHistory.setCreateUid(createUid);
            opHistory.setPlaceId(tbBizPlaceMemberCardType.getPlaceId());
            opHistory.setAmount(BigDecimal.ZERO);
            opHistory.setUid(userId);
            opHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
            opHistory.setCardTypeName(tbBizPlaceMemberCardType.getName());
            opHistory.setOpTypeName("会员注销");
            opHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount());
            opHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
            opHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
            opHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
            opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_LOGOFF);
            opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
            opHistory.setCardTypeId(tbBizPlaceMemberCardType.getId());
            if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == tbBizPlaceMemberCardType.getType()) {
                // 次卡的情况
                opHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
                opHistory.setOpAfterNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
                opHistory.setOpCardCount(tbBizPlaceMemberCard.getSurplusNumbers());
                opHistory.setOpBeforeAmount(BigDecimal.ZERO);
                opHistory.setOpAfterAmount(BigDecimal.ZERO);
            }
            TbBizPlaceMember tbBizPlaceMember = this.getPlaceMemberByUid(userId);
            if (!StringUtils.isEmpty(tbBizPlaceMember)) {
                opHistory.setUserName(tbBizPlaceMember.getUserName());
                opHistory.setMobile(tbBizPlaceMember.getMobile());
            }

            opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
            opHistory.setPlatform(platform);// APP
            // 获取订单号
            String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, userId);
            opHistory.setOrderNo(orderNo);
            String no = CommonUtils.generateNo(tbBizPlaceMemberCardType.getPlaceId());
            opHistory.setNo(no);
            addPlaceMemberCardOpRecord(opHistory);
            return opHistory;
        }
        return null;
    }

    @Override
    public ReqOrderHistory tbBizPlaceMemberOpHistory2ReqOrderHistory(TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory) {
        if (null == tbBizPlaceMemberOpHistory)
        return null;

        ReqOrderHistory reqOrderHistory = new ReqOrderHistory();
        reqOrderHistory.setPlaceId(tbBizPlaceMemberOpHistory.getPlaceId());
        reqOrderHistory.setPlaceOrderId(tbBizPlaceMemberOpHistory.getOrderNo());
        reqOrderHistory.setUid(tbBizPlaceMemberOpHistory.getUid());
        reqOrderHistory.setAmount(tbBizPlaceMemberOpHistory.getAmount());
        reqOrderHistory.setBusinessType(tbBizPlaceMemberOpHistory.getType());
        if (tbBizPlaceMemberOpHistory.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_SCENEPAY) { //1：普通订场业务 2：现场支付业务 3：竞拍业务 4：约运动
            reqOrderHistory.setSourceType((byte) 2);
        }else{
            reqOrderHistory.setSourceType((byte)1);
        }
        //0：开单 1：包场 2：门票 3：app开单 4：多种经营 5:开卡 6:充值
        // 1:开通会员 2:消费 3:退款 4:调整余额 5:充值,6：调整次卡，7:调整有效期 ,8:注销会员卡',
        if (tbBizPlaceMemberOpHistory.getSrc().byteValue() == PlaceConstants.ORDER_USE_OPEN_CARD){
            reqOrderHistory.setUseType((byte)5);
        }else if (tbBizPlaceMemberOpHistory.getSrc().byteValue() == PlaceConstants.ORDER_USE_RECHARGE_CARD){
            reqOrderHistory.setUseType((byte)6);
        }
        reqOrderHistory.setPlatform(tbBizPlaceMemberOpHistory.getPlatform());

        return reqOrderHistory;
    }

    /**
     * 根据场馆Id及共享No查询关联场馆
     * @param placeId
     * @param vipShareNo
     * @return
     */
    @Override
    public List<RespPlaceInfo> getSharePlace(Integer placeId, String vipShareNo, boolean isFilterPlaceId) {
        List<RespPlaceInfo> result = vPlaceMapper.getShareVipPlaceList(placeId, vipShareNo, isFilterPlaceId);
        return result;
    }

    @Override
    public int countPlaceMemberCard(ReqPlaceMemberSearch reqMemberSearch) {
        return vPlaceMemberMapper.countSharePlaceMemberCard(reqMemberSearch);
    }

    @Override
    public List<RespMemberCardInfo> selectMemberCardList(ReqPlaceMemberSearch reqMemberSearch) {
        return vPlaceMemberMapper.selectSharePlaceMemberCardList(reqMemberSearch);
    }

    /**
     * 通过指定场馆查询共享会员场馆集合
     * @param placeId
     * @return
     */
    public List<Integer> getShareVipPlaceIds(Integer placeId){
        return vPlaceMapper.getShareVipPlaceIds(placeId);
    }

    /**
     * 通过指定vipShareNo查询共享会员场馆集合
     * @param vipShareNo
     * @return
     */
    public List<Integer> getSharePlaceIdsByVipShareNo(String vipShareNo){
        if (org.apache.commons.lang3.StringUtils.isEmpty(vipShareNo)){
            return null;
        }
        return vPlaceMapper.getSharePlaceIdsByVipShareNo(vipShareNo);
    }

    /**
     * 更新场馆属性为共享会员
     * @param vipShareNo
     * @param placeIds
     */
    @Override
    public void updatePlaceAttachBatch(String vipShareNo, List<Integer> placeIds) {
        if (null != placeIds && placeIds.size() > 1){
            TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
            TbBizPlaceAttachExample.Criteria criterial = example.createCriteria();
            criterial.andPlaceIdIn(placeIds);

            TbBizPlaceAttach attach = new TbBizPlaceAttach();
            attach.setVipShareNo(vipShareNo); // 共享No
            attach.setIsVipShare(Constants.YES);  // 场馆支持共享会员
            tbBizPlaceAttachMapper.updateByExampleSelective(attach, example);
        }

    }

    /**
     * 批量将线上场馆支持会员卡场馆导入到redis
     */
    @Override
    public APIResponse<?> updateSupportMemberPlaceBatch() {
        List<TbBizPlaceAttach> tbBizPlaceAttachList = vPlaceMapper.selectSupportMemberPlace();
        if (CollectionUtils.isEmpty(tbBizPlaceAttachList)){
            return APIResponse.returnSuccess("没有支持会员的场馆");
        }
        //是否支持会员存放到redis
        for (TbBizPlaceAttach placeAttach : tbBizPlaceAttachList){
            String placeIdKey = PlaceConstants.CACHE_PLACE_ATTACH_INFO_PREFIX+String.valueOf(placeAttach.getPlaceId());
            placeRedisTemplate.set(placeIdKey,placeAttach,PlaceConstants.PLACE_INFO_CACHE_TIME);
        }
        return APIResponse.returnSuccess("成功添加"+tbBizPlaceAttachList.size()+"条数据到redis");
    }

    /**
     * 根据场馆ID获取场馆附属信息
     *
     * @param placeId
     * @return
     */
    public TbBizPlaceAttach getBizPlaceAttach(Integer placeId) {
        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
        }
        List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);
        if (result != null && result.size() > 0) {
            return result.get(0);
        } else {
            return null;
        }
    }

	@Override
	public void transferMemberCard(String memberCardNo, String mobile, Integer createUid) {
	    TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(memberCardNo).andIsDeleteEqualTo((byte)0).andStatusEqualTo((byte)1);
        
        List<TbBizPlaceMemberCard> TbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
        if (CollectionUtils.isEmpty(TbBizPlaceMemberCardList)) {
			throw new BizException("此会员卡无效");
		}
        TbBizPlaceMemberCard tbBizPlaceMemberCard = TbBizPlaceMemberCardList.get(0);
        
        //会员信息
        TbBizPlaceMember tbBizPlaceMember =  getPlaceMemberByUid(tbBizPlaceMemberCard.getMemberUid());
        
        Integer uid = null;
		TbBizPlaceMember otherTbBizPlaceMember = getPlaceMember(mobile);
		if (otherTbBizPlaceMember == null) {//没有注册，则先去注册
			ReqBackstageUser reqBackstageUser = new ReqBackstageUser();
	        reqBackstageUser.setMobile(mobile);
	        reqBackstageUser.setAdminUid(createUid); // 当前后台操作用户
	        reqBackstageUser.setMemberCardName(tbBizPlaceMemberCard.getCardName());
	        reqBackstageUser.setMemberName(tbBizPlaceMemberCard.getDisplayName());
	        APIResponse retUser = userServiceFacade.registerMemberUser(reqBackstageUser);
	        
	        if (null != retUser && null != retUser.getData()){
	            uid = (Integer)retUser.getData(); // 当前注册会员的uid
	        } else {
	        	throw new BizException("注册手机号失败");
	        }
	        //复制会员信息
	        tbBizPlaceMember.setId(null);
	        tbBizPlaceMember.setMobile(mobile);
	        tbBizPlaceMember.setUid(uid);
	        tbBizPlaceMember.setCreateUid(createUid);
	        tbBizPlaceMember.setMemo("转移会员卡，新手机号注册");
	        tbBizPlaceMember.setCreatTime(new Date());
	        tbBizPlaceMember.setUpdateTime(new Date());
	        tbBizPlaceMemberMapper.insertSelective(tbBizPlaceMember);
		} else {
			uid = otherTbBizPlaceMember.getUid();
		}
		 //转移会员卡到新手机号
		 TbBizPlaceMemberCard tbBizPlaceMemberCardTemp = new TbBizPlaceMemberCard();
		 tbBizPlaceMemberCardTemp.setMemberUid(uid);
		 tbBizPlaceMemberCardMapper.updateByExampleSelective(tbBizPlaceMemberCardTemp, tbBizPlaceMemberCardExample);
		 
		 // 添加日志
         businessLogService.insertIntoBusinessLog(tbBizPlaceMemberCard.getMemberUid(), PlaceConstants.LOG_TYPE_PLACE_MEMBER, createUid, "修改手机号",
                 "修改手机号:原手机号->" + tbBizPlaceMember.getMobile() + " 新手机号->" + mobile);
	}
}
